Last active
August 29, 2015 14:14
-
-
Save JLarky/3914c1d8ba99c643263f to your computer and use it in GitHub Desktop.
How to use react elements inside knockout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
span(data-bind='reactElement: someElement') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
var reactElementUmount = function (element) { | |
$(element).each(function (i, elem) { | |
React.unmountComponentAtNode(elem); | |
}); | |
}; | |
ko.bindingHandlers.reactElement = { | |
init: function (element, valueAccessor, allBindingsAccessor, viewModel) { | |
// clean up events if KO removes the element | |
ko.utils.domNodeDisposal.addDisposeCallback(element, function() { | |
reactElementUmount(element); | |
}); | |
}, | |
update: function(element, valueAccessor, allBindings) { | |
var react = ko.utils.unwrapObservable(valueAccessor()); | |
var reactElement = react && react.element; | |
if (reactElement) { | |
var reactParams = _.omit(react, ['element']) | |
$(element).each(function (i, elem) { | |
React.render(reactElement(reactParams), elem); | |
}) | |
} else { | |
reactElementUmount(element); | |
} | |
} | |
}; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var someElement = ko.observable({element: TodoApp, id: 'some id', otherProps: 123}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
render: function () { | |
console.log(this.props.id, this.props.otherProps) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment