Created
November 13, 2016 21:42
-
-
Save bsandhu/0cc660038c03e505f5d6056401c8ab77 to your computer and use it in GitHub Desktop.
Using Knockout and React together. Hook React component into 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
define( | |
['log', 'knockout', 'react', 'react-dom'], | |
function (log, ko, React, ReactDOM) { | |
"use strict"; | |
function KnockoutReactBinding() { | |
log.info('Loading KO binding for React'); | |
this.init(); | |
} | |
KnockoutReactBinding.prototype.init = function () { | |
/** | |
* This binding helps loading react component within KO space. | |
* KO wont clobber this component and its descendants. | |
* USAGE: <div data-bind="react: IronBankApp"></div> | |
*/ | |
ko.bindingHandlers.react = { | |
init: function () { | |
return {controlsDescendantBindings: true}; | |
}, | |
update: function (el, valueAccessor, allBindings) { | |
var Component = ko.unwrap(valueAccessor()); | |
var props = ko.toJS(allBindings.get('props')); | |
// Tell react to render/re-render | |
ReactDOM.render(React.createElement(Component, props), el); | |
} | |
}; | |
}; | |
return new KnockoutReactBinding(); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment