-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui-state.js
60 lines (59 loc) · 1.99 KB
/
ui-state.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
/**
* UIState manager at simplest form
* @param element
* @param initialState
* @constructor
*/
function UIState(element, initialState){
initialState = initialState || {};
this.element = element;
this.state = new Proxy(initialState, {
set: function(target, property, value){
if(initialState[property] == value) {
return false;
}
initialState[property] = value;
if(typeof this.render == 'function') {
this.render.apply(this, [initialState]);
}
}.bind(this)
});
this.render.apply(this, [initialState]);
}
UIState.prototype = {
setState: function(property, value) {
this.state[property] = value;
return this;
},
getState: function(property) {
return this.state[property];
},
render: function(initialState){
if(typeof this.state.render == 'function') {
this.element.innerHTML = '';
var content = this.state.render.apply(initialState, [this.element]);
if(typeof content == 'object') {
if(typeof content.length == 'undefined') {
// it is actual object
this.element.appendChild(content.cloneNode(true));
} else {
// it is an array
var el;
for( el = 0; el < content.length; el++) {
if(content[el] instanceof Node) {
this.element.appendChild(content[el].cloneNode(true));
}
}
}
} else {
if(typeof content !== 'undefined') {
// when something is returned, and not undefined
this.element.innerHTML = content;
}
}
if(typeof this.state.onrendered == 'function') {
this.state.onrendered.apply(initialState, [this.element, content]);
}
}
}
};