-
Notifications
You must be signed in to change notification settings - Fork 0
/
MVCObject-0.21.js
335 lines (264 loc) · 10.7 KB
/
MVCObject-0.21.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/**
Available on [GitHub](https://github.com/dcporter/mvcobject).
## Super Lightweight JS Binding & KVO
When even Angular is overkill, drop in MVCObject.js for fast, easy, lightweight binding
and KVO.
This object implements the Google Maps API's very useful MVCObject interface, documented
[here](https://developers.google.com/maps/documentation/javascript/reference#MVCObject).
This project is forked from [this](https://code.google.com/p/mvcobject-js/) excellent but
apparently abandoned one; John and Mark deserve the credit. This version tones down the
object's tendency to throw errors, making it much friendlier to use.
### Examples
Binding:
```javascript
var objectA = new MVCObject(),
objectB = new MVCObject();
// Always use setters and getters.
objectA.set('name', 'John');
objectB.set('name', 'Mark');
// Set up a binding - one line. This syncs the values, overrides the value on objectB.
objectB.bindTo('name', objectA);
objectB.get('name');
// > 'John'
objectA.set('name', 'Dave');
objectB.get('name');
// > 'Dave'
```
Key-Value Observing:
```JavaScript
var objectA = new MVCObject();
objectA.set('name', 'John');
objectA.name_changed = function() { console.log("Name changed to: " + this.get('name')); };
objectA.set('name', 'Dave');
// > "Name changed to: Dave"
```
Subclassing (obvious but very handy):
```javascript
ObjectA = function() {};
ObjectA.prototype = new MVCObject();
ObjectA.prototype.constructor = ObjectA;
```
### License
Copyright 2011 urbanplum.eu and Dave Porter. Modified from the original by
Dave Porter.
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
@author John Smith - [email protected]
@author Dave Porter - [email protected]
*/
function MVCObject(){};
MVCObject.prototype.bindTo = function(key, target, target_key, no_notify)
{
target_key = target_key || key;
var observers_value;
// Ensure the target has the property
if( !(target_key in target) )
{
throw('Undefined: property "' + target_key + '" on target object.');
}
// Is the target's property already complex?
if(! target._isPropertyBound(target_key) )
{
// Target's property is not yet a complex object. Make it one.
target[target_key] =
{
'__my_index': 0,
__observer_indexes: [],
__shared_object:
{
__value: target[target_key],
__observers: [{obj: target, key: target_key}]
}
};
}
// The target we're about to bind to has 'target_observers_length' observers already.
// We need to update the observers observers to reflect the change in offset once the arrays are merged.
var target_observers_length = target[target_key].__shared_object.__observers.length;
// Add this new observers index to the target's array of observers' indexes.
target[target_key].__observer_indexes.push(target_observers_length);
// Is this observer being observed?
if( this._isPropertyBound(key) )
{
// Make sure it's not already bound
if(this[key]['__my_index'] !== 0) return;
// Both target and observer's properties are already complex.
// We need to recursively update the observer's observers' indexes to reflect the merged observer array
this._updateObserverIndexes(key, target_observers_length);
// Merge all observers
target[target_key].__shared_object.__observers = target[target_key].__shared_object.__observers.concat(this[key].__shared_object.__observers);
// Store the observer's simple value prior to binding.
observers_value = this[key].__shared_object.__value;
}
// The observer is still a simple value.
else
{
observers_value = this[key];
// Make the observer a complex object
this[key] =
{
'__my_index': target_observers_length,
__observer_indexes : [],
__shared_object : null
};
// Add the observer to the target's array of observers
target[target_key].__shared_object.__observers.push
(
{
obj: this,
key: key
}
);
}
// Loop over all observers
for(var i in target[target_key].__shared_object.__observers)
{
// Wait until we get to the observer's observers. Check to see it is a true observer and not unbound.
if(i < target_observers_length || target[target_key].__shared_object.__observers[i] === null) continue;
// Point all observers to the common shared object
target[target_key].__shared_object.__observers[i].obj[target[target_key].__shared_object.__observers[i].key].__shared_object = target[target_key].__shared_object;
// Value has not changed or this is the first bind and no_notify was set, no need to call the callbacks.
if(target[target_key].__shared_object.__value === observers_value || (i == target_observers_length && no_notify) ) continue;
// Trigger the observer's observer's callbacks, if there are any
if(target[target_key].__shared_object.__observers[i].key + '_changed' in target[target_key].__shared_object.__observers[i].obj) target[target_key].__shared_object.__observers[i].obj[target[target_key].__shared_object.__observers[i].key + '_changed']();
}
};
/**
* Recursively update observer indexes when when new objects are added to the shared object.
*/
MVCObject.prototype._updateObserverIndexes = function(key, offset_increase)
{
// Updates the observer's index of themself
this[key]['__my_index'] += offset_increase;
for(var i in this[key].__observer_indexes)
{
// Make sure the property hasn't been unbound
if(this[key].__shared_object.__observers[this[key].__observer_indexes[i]] === null) continue;
// Recursively update observers
this[key].__shared_object.__observers[this[key].__observer_indexes[i]].obj._updateObserverIndexes(this[key].__shared_object.__observers[this[key].__observer_indexes[i]].key, offset_increase);
this[key].__observer_indexes[i] += offset_increase;
}
};
MVCObject.prototype._isPropertyBound = function(property)
{
return this[property] !== null && typeof this[property] === 'object' && '__my_index' in this[property];
};
MVCObject.prototype.get = function(key)
{
// If the property is a complex object, return the value, otherwise, return the simple value
return this._isPropertyBound(key) ? this[key].__shared_object.__value : this[key];
};
MVCObject.prototype.set = function(key, value)
{
// Does the property exist on the object
if(!key in this) throw('Cannot set value for undefined property "' + key + '".');
// Is this a bound property?
if(this._isPropertyBound(key))
{
// Has the property changed?
if(this[key].__shared_object.__value === value) return;
// Set the new value
this[key].__shared_object.__value = value;
// Call any callback's belonging to objects bound to this property
for(var i in this[key].__shared_object.__observers)
{
if(this[key].__shared_object.__observers[i] === null) continue;
if( this[key].__shared_object.__observers[i].key + '_changed' in this[key].__shared_object.__observers[i].obj) {
this[key].__shared_object.__observers[i].obj[this[key].__shared_object.__observers[i].key + '_changed']();
}
}
return;
}
// Non bound property
// Has the property changed?
if(this[key] === value) return;
// Set the value
this[key] = value;
// Manually trigger the changed event
if(key + '_changed' in this) this[key + '_changed']();
};
MVCObject.prototype.setValues = function(key_value_pairs)
{
for(var key in key_value_pairs)
{
this.set(key, key_value_pairs[key]);
}
};
/**
* Recursively re-binds observers to a new complex object
*/
MVCObject.prototype._rebindObservers = function(complex_object, key)
{
for(var i in this[key].__observer_indexes)
{
var slice;
// Make sure the observer hasn't been unbound
if(this[key].__shared_object.__observers[this[key].__observer_indexes[i]] !== null)
{
slice = this[key].__shared_object.__observers.splice(this[key].__observer_indexes[i], 1, null)[0];
// The recursive bit
slice.obj._rebindObservers(complex_object, slice.key);
// Update this object's shared object reference
slice.obj[slice.key].__shared_object = complex_object;
// Update this objects observer index
this[key].__observer_indexes.splice(i, 1, complex_object.__observers.length); // Don't need to subtract one - about to add to the array
slice.obj[slice.key]['__my_index'] = complex_object.__observers.length;
}
// This observer has been unbound
else
{
slice = null;
}
// Add the object as an observer to the new object
complex_object.__observers.push(slice);
// Update my index so I know my index as an observer in the shared object
this[key]['__my_index'] = complex_object.__observers.length;
}
};
MVCObject.prototype.unbind = function(key)
{
if( !this[key] || typeof this[key] !== 'object' || !('__my_index' in this[key]) || this[key]['__my_index'] === 0 ) return;
// Remove myself.
this[key].__shared_object.__observers[this[key]['__my_index']] = null;
// Do I have any observers (that aren't just me) ?
if(this[key].__observer_indexes.length === 0)
{
// Convert back to simple format
this[key] = this[key].__shared_object.__value;
return;
}
// I have observers. Re-bind to a new shared object.
var new_object =
{
__observers: [{obj: this, key: key}],
__value: this[key].__shared_object.__value
};
this._rebindObservers(new_object, key, 0);
this[key]['__my_index'] = 0;
this[key].__shared_object = new_object;
};
MVCObject.prototype.unbindAll = function()
{
for(var property in this)
{
if(!this._isPropertyBound(property)) continue;
this.unbind(property);
}
};
// Below are the public methods to be exported when using Google's Closure Compiler - http://code.google.com/closure/compiler/
// Uncomment if you wish to compile the code using 'advanced optimisation'.
/*
window['MVCObject'] = MVCObject;
window['MVCObject'].prototype['bindTo'] = MVCObject.prototype.bindTo;
window['MVCObject'].prototype['get'] = MVCObject.prototype.get;
window['MVCObject'].prototype['set'] = MVCObject.prototype.set;
window['MVCObject'].prototype['setValues'] = MVCObject.prototype.setValues;
window['MVCObject'].prototype['unbind'] = MVCObject.prototype.unbind;
window['MVCObject'].prototype['unbindAll'] = MVCObject.prototype.unbindAll;
*/