-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbindings.js
More file actions
69 lines (60 loc) · 2.26 KB
/
bindings.js
File metadata and controls
69 lines (60 loc) · 2.26 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
(function() {
var controllers = {};
var addController = function (name, constructor) {
//Store controller constructor
controllers[name] = {
factory: constructor,
instances: []
};
//Look for elements using the controller
var element = document.querySelector('[ng-controller=' + name + ']');
if (!element) {
return;
}
// Crate a new instance and save it
var ctrl = new controllers[name].factory();
controllers[name].instances.push(ctrl);
// Get elements bound to properties
var bindings = {};
Array.prototype.slice.call(element.querySelectorAll('[ng-bind]')).map(function (element){
var boundValue = element.getAttribute('ng-bind');
if (!bindings[boundValue]) {
bindings[boundValue] = {
boundValue: boundValue,
elements: []
}
}
bindings[boundValue].elements.push(element);
});
// Update DOM element bound when controller property is set
var proxy = new Proxy (ctrl, {
set: function (target, prop, value) {
var bind = bindings[prop];
if (bind) {
bind.elements.forEach(function (element){
element.value = value;
element.setAttribute('value', value);
});
}
return Reflect.set(target, prop, value);
}
});
// Listen DOM element update to set the controller property
Object.keys(bindings).forEach(function (boundValue){
var bind = bindings[boundValue];
bind.elements.forEach(function (element){
element.addEventListener('input', function (event){
proxy[bind.boundValue] = event.target.value;
});
})
});
// Fill proxy with ctrl properties
// and return proxy, not the ctrl!
Object.assign(proxy, ctrl);
return proxy;
}
// Export framework in window
this.angular = {
controller: addController
}
})();