-
Notifications
You must be signed in to change notification settings - Fork 66
/
child.js
115 lines (96 loc) · 2.17 KB
/
child.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
var attrs = require('attributes');
var each = require('each');
var unique = require('uniq');
var raf = require('raf-queue');
/**
* Creates a new sub-view at a node and binds
* it to the parent
*
* @param {View} view
* @param {Element} node
* @param {Function} View
*/
function ChildBinding(view, node, View) {
this.update = this.update.bind(this);
this.view = view;
this.attrs = attrs(node);
this.props = this.getProps();
var data = this.values();
data.yield = node.innerHTML;
this.child = new View(data, {
owner: view
});
this.child.replace(node);
this.child.on('destroyed', this.unbind.bind(this));
this.node = this.child.el;
this.bind();
}
/**
* Get all of the properties used in all of the attributes
*
* @return {Array}
*/
ChildBinding.prototype.getProps = function(){
var ret = [];
var view = this.view;
each(this.attrs, function(name, value){
ret = ret.concat(view.props(value));
});
return unique(ret);
};
/**
* Bind to changes on the view. Whenever a property
* changes we'll update the child with the new values.
*/
ChildBinding.prototype.bind = function(){
var self = this;
var view = this.view;
this.props.forEach(function(prop){
view.watch(prop, self.update);
});
this.send();
};
/**
* Get all the data from the node
*
* @return {Object}
*/
ChildBinding.prototype.values = function(){
var view = this.view;
var ret = {};
each(this.attrs, function(name, value){
ret[name] = view.interpolate(value);
});
return ret;
};
/**
* Send the data to the child
*/
ChildBinding.prototype.send = function(){
this.child.set(this.values());
};
/**
* Unbind this view from the parent
*/
ChildBinding.prototype.unbind = function(){
var view = this.view;
var update = this.update;
this.props.forEach(function(prop){
view.unwatch(prop, update);
});
if (this.job) {
raf.cancel(this.job);
}
};
/**
* Update the child view will updated values from
* the parent. This will batch changes together
* and only fire once per tick.
*/
ChildBinding.prototype.update = function(){
if (this.job) {
raf.cancel(this.job);
}
this.job = raf(this.send, this);
};
module.exports = ChildBinding;