forked from lelandrichardson/knockout-react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (62 loc) · 2.24 KB
/
index.js
File metadata and controls
70 lines (62 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*!
* knockout-react - wrapper/bridge for using Knockout with React.js and React.js with Knockout
*
* Copyright (c) 2016 Leland Richardson
* Licensed under the terms of the MIT license
*/
!function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['react', 'knockout'], factory);
} else if (typeof exports === 'object') {
factory(require('react'), require('knockout'));
} else {
factory(root.React, root.ko);
}
}
(this, function(React, ko) {
var KnockoutMixin = {
updateKnockout() {
this.__koTrigger(!this.__koTrigger());
},
componentDidMount() {
this.__koTrigger = ko.observable(true);
this.__koModel = ko.computed(function() {
this.__koTrigger(); // subscribe to changes of this
return {
props: this.props,
state: this.state
};
}, this);
ko.applyBindings(this.__koModel, this.getDOMNode());
},
componentWillUnmount() {
ko.cleanNode(this.getDOMNode());
},
componentDidUpdate() {
this.updateKnockout();
}
};
// <ul data-bind="react: { $: ToDoList, props: $data }><ul>
var reactHandler = ko.bindingHandlers.react = {
render: function(el, Component, props) {
React.render(
React.createElement(Component, props),
el
);
},
init: function(el, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = valueAccessor();
var Component = ko.unwrap(options.component || options.$);
var props = ko.toJS(options.props || viewModel);
reactHandler.render(el, Component, props);
return { controlsDescendantBindings: true };
},
update: function(el, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = valueAccessor();
var Component = ko.unwrap(options.component || options.$);
var props = ko.toJS(options.props || viewModel);
reactHandler.render(el, Component, props);
return { controlsDescendantBindings: true };
}
};
});