-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.js
117 lines (90 loc) · 2.84 KB
/
hub.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
;(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['regularjs'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('regularjs'));
} else {
window.Hub = factory(root.Regular);
}
}(this, function( Regular ) {
var slice = Regular.util.slice,
msie = Regular.dom.msie,
config = Regular.config || {BEGIN: "{{", END: "}}"};
var util = function(){
var rEvent = /^on-(\w+)$/,
rExpression = new RegExp("^" + config.BEGIN + "(.*)" + config.END + "$");
function getAttrs( element ){
var attrs = element.attributes, len = attrs && attrs.length,
attr, passedAttr = [];
if(len){
for( var i = 0; i < len; i++ ){
if(!msie || msie > 8 || attrs[i].specified){
attr = attrs[i]
passedAttr.push(attr);
}
}
}
return passedAttr;
}
function getEventName(str){
var matched = rEvent.exec(str);
return matched && matched[1];
}
function getExpression(str){
var matched = rExpression.exec(str) ;
return matched && matched[1] && Regular.expression(matched[1]);
}
return {
getAttrs: getAttrs,
getEventName: getEventName,
getExpression: getExpression
}
}();
var Hub = Regular.extend({
scope: Regular,
init: function initHub(){
var scope = this.scope;
this._initComponents(scope._components);
},
_initComponents: function(components){
var Component;
for( var i in components ){
Component = components[i];
if( Component){
this._initComponent(i, Component);
}
}
},
_initComponent: function(name, Component){
var container = this.container || document.body;
var nodes = slice( container.getElementsByTagName(name) );
nodes.forEach(this._initTag.bind(this, Component));
},
_initTag: function(Component, node){
var attrs = util.getAttrs(node);
var data = {}, events = {},
watchers = {}, context = this;
attrs.forEach(function(attr){
var value = attr.value,
name = attr.name, expression, eventName;
eventName = util.getEventName(name);
if( !eventName ){ // data
expression = util.getExpression(value);
if( !expression ){
data[name] = value
}else{
watchers[name] = expression;
data[name] = expression.get(context);
}
}else{ //event bind
events[eventName] = Regular.util.handleEvent.call(context, value, eventName);
}
})
var component = new Component({data: data, events: events, $parent: this});
component.$bind(this, watchers);
component.$inject(node, 'after');
node.parentNode.removeChild(node);
}
});
return Hub;
}));