Skip to content

Instantly share code, notes, and snippets.

@luggage66
Last active December 22, 2016 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luggage66/720d8f8d2480f9cb09c668e8dc88714b to your computer and use it in GitHub Desktop.
Save luggage66/720d8f8d2480f9cb09c668e8dc88714b to your computer and use it in GitHub Desktop.
Knockout React BindingHandler. Fiddle: https://jsfiddle.net/luggage66/yoofaaqr/
// Inspired by http://www.intelligiblebabble.com/making-reactjs-and-knockoutjs-play-nice
import ko from 'knockout';
import ReactDOM from 'react-dom';
const reactBindingHandler = {
init(element, valueAccessor, allBindings, viewModel, bindingContext) {
// make sure we cleanup, later.
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
ReactDOM.unmountComponentAtNode(element);
});
// and tell knockout to keep it's grubby mitts out of the react-generated DOM
return { controlsDescendantBindings: true };
},
update(element, valueAccessor, allBindings, viewModel, bindingContext) {
const renderFn = ko.unwrap(valueAccessor());
// call the function provided. Assuming the function reads observables,
// they will be observed so that this component updates.
const componentTree = renderFn.call(viewModel);
// (re)render.
ReactDOM.render(componentTree, element);
}
};
ko.bindingHandlers.react = reactBindingHandler;
export default reactBindingHandler;
Enter Name: <input data-bind="value: name" />
You Entered:
<div data-bind="react: renderSomeReactComponent"></div>
import ko from 'knockout';
import React from 'react';
class MyViewModel {
constructor() {
this.name = ko.observable('Jimbo');
}
// will re-render then observable change.
renderSomeReactComponent() {
return <p>{this.name()}</p>;
}
}
let myViewModel = new MyViewModel();
ko.applyBindings(myViewModel);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment