Last active
December 22, 2016 00:43
-
-
Save luggage66/720d8f8d2480f9cb09c668e8dc88714b to your computer and use it in GitHub Desktop.
Knockout React BindingHandler. Fiddle: https://jsfiddle.net/luggage66/yoofaaqr/
This file contains hidden or 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
// 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; |
This file contains hidden or 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
Enter Name: <input data-bind="value: name" /> | |
You Entered: | |
<div data-bind="react: renderSomeReactComponent"></div> |
This file contains hidden or 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
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