forked from kamicane/art
-
Notifications
You must be signed in to change notification settings - Fork 101
/
native.js
83 lines (70 loc) · 1.87 KB
/
native.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
var Class = require('../core/class');
function elementFrom(node){
if (node.toElement) return node.toElement();
if (node.getDOMNode) return node.getDOMNode();
if (node.getNode) return node.getNode();
return node;
}
module.exports = Class({
// conventions
toElement: function(){
return this.element;
},
getDOMNode: function(){
return this.toElement();
},
getNode: function(){
return this.toElement();
},
// placement
inject: function(container){
(container.containerElement || elementFrom(container))
.appendChild(this.element);
return this;
},
injectBefore: function(sibling){
var element = elementFrom(sibling);
element.parentNode.insertBefore(this.element, element);
return this;
},
eject: function(){
var element = this.element, parent = element.parentNode;
if (parent) parent.removeChild(element); // TODO: VML Nodes are dead after being ejected
return this;
},
// events
subscribe: function(type, fn, bind){
if (typeof type != 'string'){ // listen type / fn with object
var subscriptions = [];
for (var t in type) subscriptions.push(this.subscribe(t, type[t]));
return function(){ // unsubscribe
for (var i = 0, l = subscriptions.length; i < l; i++)
subscriptions[i]();
return this;
};
} else { // listen to one
if (!bind) bind = this;
var bound;
if (typeof fn === 'function'){
bound = fn.bind ? fn.bind(bind)
: function(){ return fn.apply(bind, arguments); };
} else {
bound = fn;
}
var element = this.element;
if (element.addEventListener){
element.addEventListener(type, bound, false);
return function(){ // unsubscribe
element.removeEventListener(type, bound, false);
return this;
};
} else {
element.attachEvent('on' + type, bound);
return function(){ // unsubscribe
element.detachEvent('on' + type, bound);
return this;
};
}
}
}
});