/
observe.js
2048 lines (1985 loc) · 67.5 KB
/
observe.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 1.69
steal('can/util','can/util/bind','can/construct', function(can, bind) {
// ## observe.js
// `can.Observe`
// _Provides the observable pattern for JavaScript Objects._
//
// Returns `true` if something is an object with properties of its own.
var canMakeObserve = function( obj ) {
return obj && !can.isDeferred(obj) && (can.isArray(obj) || can.isPlainObject( obj ) || ( obj instanceof can.Observe ));
},
// Removes all listeners.
unhookup = function(items, namespace){
return can.each(items, function(item){
if(item && item.unbind){
item.unbind("change" + namespace);
}
});
},
// Listens to changes on `child` and "bubbles" the event up.
// `child` - The object to listen for changes on.
// `prop` - The property name is at on.
// `parent` - The parent object of prop.
// `ob` - (optional) The Observe object constructor
// `list` - (optional) The observable list constructor
hookupBubble = function( child, prop, parent, Ob, List ) {
Ob = Ob || Observe;
List = List || Observe.List;
// If it's an `array` make a list, otherwise a child.
if (child instanceof Observe){
// We have an `observe` already...
// Make sure it is not listening to this already
// It's only listening if it has bindings already.
parent._bindings &&unhookup([child], parent._cid);
} else if ( can.isArray(child) ) {
child = new List(child);
} else {
child = new Ob(child);
}
// only listen if something is listening to you
if(parent._bindings){
// Listen to all changes and `batchTrigger` upwards.
bindToChildAndBubbleToParent(child, prop, parent)
}
return child;
},
bindToChildAndBubbleToParent = function(child, prop, parent){
child.bind("change" + parent._cid,
function( /* ev, attr */ ) {
// `batchTrigger` the type on this...
var args = can.makeArray(arguments),
ev = args.shift();
args[0] = (prop === "*" ?
[ parent.indexOf( child ), args[0]] :
[ prop, args[0]] ).join(".");
// track objects dispatched on this observe
ev.triggeredNS = ev.triggeredNS || {};
// if it has already been dispatched exit
if (ev.triggeredNS[parent._cid]) {
return;
}
ev.triggeredNS[parent._cid] = true;
// send change event with modified attr to parent
can.trigger(parent, ev, args);
// send modified attr event to parent
//can.trigger(parent, args[0], args);
});
},
// An `id` to track events for a given observe.
observeId = 0,
// A helper used to serialize an `Observe` or `Observe.List`.
// `observe` - The observable.
// `how` - To serialize with `attr` or `serialize`.
// `where` - To put properties, in an `{}` or `[]`.
serialize = function( observe, how, where ) {
// Go through each property.
observe.each(function( val, name ) {
// If the value is an `object`, and has an `attrs` or `serialize` function.
where[name] = canMakeObserve(val) && can.isFunction( val[how] ) ?
// Call `attrs` or `serialize` to get the original data back.
val[how]() :
// Otherwise return the value.
val;
});
return where;
},
attrParts = function(attr, keepKey) {
if(keepKey) {
return [attr];
}
return can.isArray(attr) ? attr : (""+attr).split(".");
},
// Which batch of events this is for -- might not want to send multiple
// messages on the same batch. This is mostly for event delegation.
batchNum = 1,
// how many times has start been called without a stop
transactions = 0,
// an array of events within a transaction
batchEvents = [],
stopCallbacks = [],
makeBindSetup = function(wildcard){
return function(){
var parent = this;
this._each(function(child, prop){
if(child && child.bind){
bindToChildAndBubbleToParent(child, wildcard || prop, parent)
}
})
};
};
/**
* @add can.Observe
*/
//
var Observe = can.Map = can.Observe = can.Construct( {
/**
* @static
*/
// keep so it can be overwritten
bind : can.bindAndSetup,
unbind: can.unbindAndTeardown,
id: "id",
canMakeObserve : canMakeObserve,
// starts collecting events
// takes a callback for after they are updated
// how could you hook into after ejs
/**
* @function can.Observe.startBatch startBatch
* @parent can.Observe.static
* @description Begin an event batch.
*
* @signature `can.Observe.startBatch([batchStopHandler])`
*
* @param {Function} [batchStopHandler] a callback that gets called after all batched events have been called
*
* @body
* `startBatch` causes can.Observe to begin an event batch. Until `[can.Observe.stopBatch]` is called, any
* events that would result from calls to `[can.Observe::attr attr]` are held back from firing. If you have
* lots of changes to make to can.Observes, batching them together can help performance &emdash; especially if
* those can.Observes are live-bound to the DOM.
*
* In this example, you can see how the _first_ and _change_ events are not fired (and their handlers
* are not called) until `stopBatch` is called.
*
* @codestart
* var person = new can.Observe({
* first: 'Alexis',
* last: 'Abril'
* });
*
* person.bind('first', function() {
* console.log("First name changed."");
* }).bind('change', function() {
* console.log("Something changed.");
* });
*
* can.Observe.startBatch();
* person.attr('first', 'Alex');
* console.log('Still in the batch.');
* can.Observe.stopBatch();
*
* // the log has:
* // Still in the batch.
* // First name changed.
* // Something changed.
* @codeend
*
* You can also pass a callback to `startBatch` which will be called after all the events have
* been fired:
* @codestart
* can.Observe.startBatch(function() {
* console.log('The batch is over.');
* });
* person.attr('first', 'Izzy');
* console.log('Still in the batch.');
* can.Observe.stopBatch();
*
* // The console has:
* // Still in the batch.
* // First name changed.
* // Something changed.
* // The batch is over.
* @codeend
*
* ## Calling `startBatch` multiple times
*
* If you call `startBatch` more than once, `stopBatch` needs to be called
* the same number of times before any batched events will fire. For ways
* to circumvent this process, see [can.Observe.stopBatch].
*
* Here is an example that demonstrates how events are affected by calling
* `startBatch` multiple times.
*
* @codestart
* var addPeople = function(observable) {
* can.Observe.startBatch();
* observable.attr('a', 'Alice');
* observable.attr('b', 'Bob');
* observable.attr('e', 'Eve');
* can.Observe.stopBatch();
* };
*
* // In a completely different place:
* var list = new can.Observe();
* list.bind('change', function() {
* console.log('The list changed.');
* });
*
* can.Observe.startBatch();
* addPeople(list);
* console.log('Still in the batch.');
*
* // Here, the console has:
* // Still in the batch.
*
* can.Observe.stopBatch();
*
* // Here, the console has:
* // Still in the batch.
* // The list changed.
* // The list changed.
* // The list changed.
* @codeend
*/
startBatch: function( batchStopHandler ) {
transactions++;
batchStopHandler && stopCallbacks.push(batchStopHandler);
},
/**
* @function can.Observe.stopBatch stopBatch
* @parent can.Observe.static
* @description End an event batch.
* @signature `can.Observe.stopBatch([force[, callStart]])`
* @param {bool} [force=false] whether to stop batching events immediately
* @param {bool} [callStart=false] whether to call `[can.Observe.startBatch startBatch]` after firing batched events
*
* @body
* `stopBatch` matches an earlier `[can.Observe.startBatch]` call. If `stopBatch` has been
* called as many times as `startBatch` (or if _force_ is true), all batched events will be
* fired and any callbacks passed to `startBatch` since the beginning of the batch will be
* called. If _force and _callStart_ are both true, a new batch will be started when all
* the events and callbacks have been fired.
*
* See `[can.Observe.startBatch]` for examples of `startBatch` and `stopBatch` in normal use.
*
* In this example, the batch is forceably ended in the `addPeople` function.
* @codestart
* var addPeople = function(observable) {
* can.Observe.startBatch();
* observable.attr('a', 'Alice');
* observable.attr('b', 'Bob');
* observable.attr('e', 'Eve');
* can.Observe.stopBatch(true);
* };
*
* // In a completely different place:
* var list = new can.Observe();
* list.bind('change', function() {
* console.log('The list changed.');
* });
*
* can.Observe.startBatch();
* addPeople(list);
* console.log('Still in the batch.');
*
* // Here, the console has:
* // Still in the batch.
*
* can.Observe.stopBatch();
*
* // Here, the console has:
* // The list changed.
* // The list changed.
* // The list changed.
* // Still in the batch.
* @codeend
*/
stopBatch: function(force, callStart){
if(force){
transactions = 0;
} else {
transactions--;
}
if(transactions == 0){
var items = batchEvents.slice(0),
callbacks = stopCallbacks.slice(0);
batchEvents= [];
stopCallbacks = [];
batchNum++;
callStart && this.startBatch();
can.each(items, function( args ) {
can.trigger.apply(can, args);
});
can.each(callbacks, function( cb ) {
cb();
});
}
},
/**
* @function can.Observe.triggerBatch triggerBatch
* @parent can.Observe.static
* @description Trigger an event to be added to the current batch.
* @signature `can.Observe.triggerBatch(item, event [, args])`
* @param {can.Observe} item the target of the event
* @param {String|{type: String}} event the type of event, or an event object with a type given
* @param {Array} [args] the parameters to trigger the event with.
*
* @body
* If events are currently being batched, calling `triggerBatch` adds an event
* to the batch. If events are not currently being batched, the event is triggered
* immediately.
*/
triggerBatch: function( item, event, args ) {
// Don't send events if initalizing.
if ( ! item._init) {
if (transactions == 0 ) {
return can.trigger(item, event, args);
} else {
event = typeof event === "string" ?
{ type: event } :
event;
event.batchNum = batchNum;
batchEvents.push([
item,
event,
args ] );
}
}
},
/**
* @function can.Observe.keys keys
* @parent can.Observe.static
* @description Iterate over the keys of an Observe.
* @signature `can.Observe.keys(observe)`
* @param {can.Observe} observe the `can.Observe` to get the keys from
* @return {Array} array An array containing the keys from _observe_.
*
* @body
* `keys` iterates over an observe to get an array of its keys.
*
* @codestart
* var people = new can.Observe({
* a: 'Alice',
* b: 'Bob',
* e: 'Eve'
* });
*
* can.Observe.keys(people); // ['a', 'b', 'e']
* @codeend
*/
keys: function(observe) {
var keys = [];
Observe.__reading && Observe.__reading(observe, '__keys');
for(var keyName in observe._data) {
keys.push(keyName);
}
return keys;
}
},
/**
* @prototype
*/
{
setup: function( obj ) {
// `_data` is where we keep the properties.
this._data = {};
/**
* @property {String} can.Observe.prototype._cid
* @hide
*
* A globally unique ID for this `can.Observe` instance.
*/
// The namespace this `object` uses to listen to events.
can.cid(this, ".observe");
// Sets all `attrs`.
this._init = 1;
this.attr(obj);
this.bind('change'+this._cid,can.proxy(this._changes,this));
delete this._init;
},
_bindsetup: makeBindSetup(),
_bindteardown: function(){
var cid = this._cid;
this._each(function(child){
unhookup([child], cid)
})
},
_changes: function(ev, attr, how,newVal, oldVal){
Observe.triggerBatch(this, {type:attr, batchNum: ev.batchNum}, [newVal,oldVal]);
},
_triggerChange: function(attr, how,newVal, oldVal){
Observe.triggerBatch(this,"change",can.makeArray(arguments))
},
// no live binding iterator
_each: function(callback){
var data = this.__get();
for(var prop in data){
if(data.hasOwnProperty(prop)){
callback(data[prop],prop)
}
}
},
/**
* @function can.Observe.prototype.attr attr
* @description Get or set properties on an Observe.
* @signature `observe.attr()`
*
* Gets a collection of all the properties in this `can.Observe`.
*
* @return {Object<String, *>} an object with all the properties in this `can.Observe`.
*
* @signature `observe.attr(key)`
*
* Reads a property from this `can.Observe`.
*
* @param {String} key the property to read
* @return {*} the value assigned to _key_.
*
* @signature `observe.attr(key, value)`
*
* Assigns _value_ to a property on this `can.Observe` called _key_.
*
* @param {String} key the property to set
* @param {*} the value to assign to _key_.
* @return {can.Observe} this Observe, for chaining
*
* @signature `observe.attr(obj[, removeOthers])`
*
* Assigns each value in _obj_ to a property on this `can.Observe` named after the
* corresponding key in _obj_, effectively merging _obj_ into the Observe.
*
* @param {Object<String, *>} obj a collection of key-value pairs to set.
* If any properties already exist on the `can.Observe`, they will be overwritten.
*
* @param {bool} [removeOthers=false] whether to remove keys not present in _obj_.
* To remove keys without setting other keys, use `[can.Observe::removeAttr removeAttr]`.
*
* @return {can.Observe} this Observe, for chaining
*
* @body
* `attr` gets or sets properties on the `can.Observe` it's called on. Here's a tour through
* how all of its forms work:
*
* @codestart
* var people = new can.Observe({});
*
* // set a property:
* people.attr('a', 'Alex');
*
* // get a property:
* people.attr('a'); // 'Alex'
*
* // set and merge multiple properties:
* people.attr({
* a: 'Alice',
* b: 'Bob'
* });
*
* // get all properties:
* people.attr(); // {a: 'Alice', b: 'Bob'}
*
* // set properties while removing others:
* people.attr({
* b: 'Bill',
* e: 'Eve'
* }, true);
*
* people.attr(); // {b: 'Bill', e: 'Eve'}
* @codeend
*
* ## Deep properties
*
* `attr` can also set and read deep properties. All you have to do is specify
* the property name as you normally would if you weren't using `attr`.
*
* @codestart
* var people = new can.Observe({names: {}});
*
* // set a property:
* people.attr('names.a', 'Alice');
*
* // get a property:
* people.attr('names.a'); // 'Alice'
* people.names.attr('a'); // 'Alice'
*
* // get all properties:
* people.attr(); // {names: {a: 'Alice'}}
* @codeend
*
* Objects that are added to Observes become Observes themselves behind the scenes,
* so changes to deep properties fire events at each level, and you can bind at any
* level. As this example shows, all the same events are fired no matter what level
* you call `attr` at:
*
* @codestart
* var people = new can.Observe({names: {}});
*
* people.bind('change', function(ev, attr, how, newVal, oldVal) {
* console.log('people change: ' + attr + ', ' + how + ', ' + newVal + ', ' + oldVal);
* });
*
* people.names.bind('change', function(ev, attr, how, newVal, oldVal) {
* console.log('people.names change' + attr + ', ' + how + ', ' + newVal + ', ' + oldVal);
* });
*
* people.bind('names', function(ev, newVal, oldVal) {
* console.log('people names: ' + newVal + ', ' + oldVal);
* });
*
* people.names.bind('a', function(ev, newVal, oldVal) {
* console.log('people.names a: ' + newVal + ', ' + oldVal);
* });
*
* people.bind('names.a', function(ev, newVal, oldVal) {
* console.log('people names.a: ' + newVal + ', ' + oldVal);
* });
*
* people.attr('names.a', 'Alice'); // people change: names.a, add, Alice, undefined
* // people.names change: a, add, Alice, undefined
* // people.names a: Alice, undefined
* // people names.a: Alice, undefined
*
* people.names.attr('b', 'Bob'); // people change: names.b, add, Bob, undefined
* // people.names change: b, add, Bob, undefined
* // people.names b: Bob, undefined
* // people names.b: Bob, undefined
* @codeend
*
* ## See also
*
* For information on the events that are fired on property changes and how
* to listen for those events, see [can.Observe.prototype.bind bind].
*/
attr: function( attr, val ) {
// This is super obfuscated for space -- basically, we're checking
// if the type of the attribute is not a `number` or a `string`.
var type = typeof attr;
if ( type !== "string" && type !== "number" ) {
return this._attrs(attr, val)
} else if ( arguments.length === 1 ) {// If we are getting a value.
// Let people know we are reading.
Observe.__reading && Observe.__reading(this, attr)
return this._get(attr)
} else {
// Otherwise we are setting.
this._set(attr, val);
return this;
}
},
/**
* @function can.Observe.prototype.each each
* @description Call a function on each property of an Observe.
* @signature `observe.each( callback(item, propName ) )`
*
* `each` iterates through the Observe, calling a function
* for each property value and key.
*
* @param {function(*,String)} callback(item,propName) the function to call for each property
* The value and key of each property will be passed as the first and second
* arguments, respectively, to the callback. If the callback returns false,
* the loop will stop.
*
* @return {can.Observe} this Observe, for chaining
*
* @body
* @codestart
* var names = [];
* new can.Observe({a: 'Alice', b: 'Bob', e: 'Eve'}).each(function(value, key) {
* names.push(value);
* });
*
* names; // ['Alice', 'Bob', 'Eve']
*
* names = [];
* new can.Observe({a: 'Alice', b: 'Bob', e: 'Eve'}).each(function(value, key) {
* names.push(value);
* if(key === 'b') {
* return false;
* }
* });
*
* names; // ['Alice', 'Bob']
*
* @codeend
*/
each: function() {
Observe.__reading && Observe.__reading(this, '__keys');
return can.each.apply(undefined, [this.__get()].concat(can.makeArray(arguments)))
},
/**
* @function can.Observe.prototype.removeAttr removeAttr
* @description Remove a property from an Observe.
* @signature `observe.removeAttr(attrName)`
* @param {String} attrName the name of the property to remove
* @return {*} the value of the property that was removed
*
* @body
* `removeAttr` removes a property by name from an Observe.
*
* @codestart
* var people = new can.Observe({a: 'Alice', b: 'Bob', e: 'Eve'});
*
* people.removeAttr('b'); // 'Bob'
* people.attr(); // {a: 'Alice', e: 'Eve'}
* @codeend
*
* Removing an attribute will cause a _change_ event to fire with `'remove'`
* passed as the _how_ parameter and `undefined` passed as the _newVal_ to
* handlers. It will also cause a _property name_ event to fire with `undefined`
* passed as _newVal_. An in-depth description at these events can be found
* under `[can.Observe.prototype.attr attr]`.
*/
removeAttr: function( attr ) {
// Info if this is List or not
var isList = this instanceof can.Observe.List,
// Convert the `attr` into parts (if nested).
parts = attrParts(attr),
// The actual property to remove.
prop = parts.shift(),
// The current value.
current = isList ? this[prop] : this._data[prop];
// If we have more parts, call `removeAttr` on that part.
if ( parts.length ) {
return current.removeAttr(parts)
} else {
if(isList) {
this.splice(prop, 1)
} else if( prop in this._data ){
// Otherwise, `delete`.
delete this._data[prop];
// Create the event.
if (!(prop in this.constructor.prototype)) {
delete this[prop]
}
// Let others know the number of keys have changed
Observe.triggerBatch(this, "__keys");
this._triggerChange(prop, "remove", undefined, current);
}
return current;
}
},
// Reads a property from the `object`.
_get: function( attr ) {
var value = typeof attr === 'string' && !!~attr.indexOf('.') && this.__get(attr);
if(value) {
return value;
}
// break up the attr (`"foo.bar"`) into `["foo","bar"]`
var parts = attrParts(attr),
// get the value of the first attr name (`"foo"`)
current = this.__get(parts.shift());
// if there are other attributes to read
return parts.length ?
// and current has a value
current ?
// lookup the remaining attrs on current
current._get(parts) :
// or if there's no current, return undefined
undefined
:
// if there are no more parts, return current
current;
},
// Reads a property directly if an `attr` is provided, otherwise
// returns the "real" data object itself.
__get: function( attr ) {
return attr ? this._data[attr] : this._data;
},
// Sets `attr` prop as value on this object where.
// `attr` - Is a string of properties or an array of property values.
// `value` - The raw value to set.
_set: function( attr, value, keepKey) {
// Convert `attr` to attr parts (if it isn't already).
var parts = attrParts(attr, keepKey),
// The immediate prop we are setting.
prop = parts.shift(),
// The current value.
current = this.__get(prop);
// If we have an `object` and remaining parts.
if ( canMakeObserve(current) && parts.length ) {
// That `object` should set it (this might need to call attr).
current._set(parts, value)
} else if (!parts.length ) {
// We're in "real" set territory.
if(this.__convert){
value = this.__convert(prop, value)
}
this.__set(prop, value, current)
} else {
throw "can.Observe: Object does not exist"
}
},
__set : function(prop, value, current){
// Otherwise, we are setting it on this `object`.
// TODO: Check if value is object and transform
// are we changing the value.
if ( value !== current ) {
// Check if we are adding this for the first time --
// if we are, we need to create an `add` event.
var changeType = this.__get().hasOwnProperty(prop) ? "set" : "add";
// Set the value on data.
this.___set(prop,
// If we are getting an object.
canMakeObserve(value) ?
// Hook it up to send event.
hookupBubble(value, prop, this) :
// Value is normal.
value);
if(changeType == "add"){
// If there is no current value, let others know that
// the the number of keys have changed
Observe.triggerBatch(this, "__keys", undefined);
}
// `batchTrigger` the change event.
this._triggerChange(prop, changeType, value, current);
//Observe.triggerBatch(this, prop, [value, current]);
// If we can stop listening to our old value, do it.
current && unhookup([current], this._cid);
}
},
// Directly sets a property on this `object`.
___set: function( prop, val ) {
this._data[prop] = val;
// Add property directly for easy writing.
// Check if its on the `prototype` so we don't overwrite methods like `attrs`.
if (!(prop in this.constructor.prototype)) {
this[prop] = val
}
},
/**
* @function can.Observe.prototype.bind bind
* @description Bind event handlers to an Observe.
*
* @signature `observe.bind(eventType, handler)`
*
* @param {String} eventType the type of event to bind this handler to
* @param {Function} handler the handler to be called when this type of event fires
* The signature of the handler depends on the type of event being bound. See below
* for details.
* @return {can.Observe} this Observe, for chaining
*
* @body
* `bind` binds event handlers to property changes on `can.Observe`s. When you change
* a property using `attr`, two events are fired on the Observe, allowing other parts
* of your application to observe the changes to the object.
*
* ## The _change_ event
*
* The first event that is fired is the _change_ event. The _change_ event is useful
* if you want to react to all changes on an Observe.
*
* @codestart
* var o = new can.Observe({});
* o.bind('change', function(ev, attr, how, newVal, oldVal) {
* console.log('Something changed.');
* });
* @codeend
*
* The parameters of the event handler for the _change_ event are:
*
* - _ev_ The event object.
* - _attr_ Which property changed.
* - _how_ Whether the property was added, removed, or set. Possible values are `'add'`, `'remove'`, or `'set'`.
* - _newVal_ The value of the property after the change. `newVal` will be `undefined` if the property was removed.
* - _oldVal_ Thishe value of the property before the change. `oldVal` will be `undefined` if the property was added.
*
* Here is a concrete tour through the _change_ event handler's arguments:
*
* @codestart
* var o = new can.Observe({});
* o.bind('change', function(ev, attr, how, newVal, oldVal) {
* console.log(ev + ', ' + attr + ', ' + how + ', ' + newVal + ', ' + oldVal);
* });
*
* o.attr('a', 'Alexis'); // [object Object], a, add, Alexis, undefined
* o.attr('a', 'Adam'); // [object Object], a, set, Adam, Alexis
* o.attr({
* 'a': 'Alice', // [object Object], a, set, Alice, Adam
* 'b': 'Bob' // [object Object], b, add, Bob, undefined
* });
* o.removeAttr('a'); // [object Object], a, remove, undefined, Alice
* @codeend
*
* (See also `[can.Observe::removeAttr removeAttr]`, which removes properties).
*
* ## The _property name_ event
*
* The second event that is fired is an event whose type is the same as the changed
* property's name. This event is useful for noticing changes to a specific property.
*
* @codestart
* var o = new can.Observe({});
* o.bind('a', function(ev, newVal, oldVal) {
* console.log('The value of a changed.');
* });
* @codeend
*
* The parameters of the event handler for the _property name_ event are:
*
* - _ev_ The event object.
* - _newVal_ The value of the property after the change. `newVal` will be `undefined` if the property was removed.
* - _oldVal_ The value of the property before the change. `oldVal` will be `undefined` if the property was added.
*
* Here is a concrete tour through the _property name_ event handler's arguments:
*
* @codestart
* var o = new can.Observe({});
* o.bind('a', function(ev, newVal, oldVal) {
* console.log(ev + ', ' + newVal + ', ' + oldVal);
* });
*
* o.attr('a', 'Alexis'); // [object Object], Alexis, undefined
* o.attr('a', 'Adam'); // [object Object], Adam, Alexis
* o.attr({
* 'a': 'Alice', // [object Object], Alice, Adam
* 'b': 'Bob'
* });
* o.removeAttr('a'); // [object Object], undefined, Alice
* @codeend
*
* ## See also
*
* More information about changing properties on Observes can be found under
* [can.Observe.prototype.attr attr].
*
* For a more specific way to changes on Observes, see the [can.Observe.delegate] plugin.
*/
bind: can.bindAndSetup,
/**
* @function can.Observe.prototype.unbind unbind
* @description Unbind event handlers from an Observe.
* @signature `observe.unbind(eventType[, handler])`
* @param {String} eventType the type of event to unbind, exactly as passed to `bind`
* @param {Function} [handler] the handler to unbind
*
* @body
* `unbind` unbinds event handlers previously bound with [can.Observe.prototype.bind|`bind`].
* If no _handler_ is passed, all handlers for the given event type will be unbound.
*
* @codestart
* var i = 0,
* increaseBy2 = function() { i += 2; },
* increaseBy3 = function() { i += 3; },
* o = new can.Observe();
*
* o.bind('change', increaseBy2);
* o.bind('change', increaseBy3);
* o.attr('a', 'Alice');
* i; // 5
*
* o.unbind('change', increaseBy2);
* o.attr('b', 'Bob');
* i; // 8
*
* o.unbind('change');
* o.attr('e', 'Eve');
* i; // 8
* @codeend
*/
unbind: can.unbindAndTeardown,
/**
* @function can.Observe.prototype.serialize serialize
* @description Serialize this object to something that
* can be passed to `JSON.stringify`.
* @signature `observe.serialize()`
*
*
* Get the serialized Object form of the observe. Serialized
* data is typically used to send back to a server.
*
* o.serialize() //-> { name: 'Justin' }
*
* Serialize currently returns the same data
* as [can.Observe.prototype.attrs]. However, in future
* versions, serialize will be able to return serialized
* data similar to [can.Model]. The following will work:
*
* new Observe({time: new Date()})
* .serialize() //-> { time: 1319666613663 }
*
* @return {Object} a JavaScript Object that can be
* serialized with `JSON.stringify` or other methods.
*
*/
serialize: function() {
return serialize(this, 'serialize', {});
},
/**
* @hide
* Set multiple properties on the observable
* @param {Object} props
* @param {Boolean} remove true if you should remove properties that are not in props
*/
_attrs: function( props, remove ) {
if ( props === undefined ) {
return serialize(this, 'attr', {})
}
props = can.extend({}, props);
var prop,
self = this,
newVal;
Observe.startBatch();
this.each(function(curVal, prop){
newVal = props[prop];
// If we are merging...
if ( newVal === undefined ) {
remove && self.removeAttr(prop);
return;
}
if(self.__convert){
newVal = self.__convert(prop, newVal)
}
// if we're dealing with models, want to call _set to let converter run
if( newVal instanceof can.Observe ) {
self.__set(prop, newVal, curVal)
// if its an object, let attr merge
} else if ( canMakeObserve(curVal) && canMakeObserve(newVal) && curVal.attr ) {
curVal.attr(newVal, remove)
// otherwise just set
} else if ( curVal != newVal ) {
self.__set(prop, newVal, curVal)
}
delete props[prop];
})
// Add remaining props.
for ( var prop in props ) {
newVal = props[prop];
this._set(prop, newVal, true)
}
Observe.stopBatch()
return this;
},
/**
* @function can.Observe.prototype.compute compute
* @description Make a can.compute from an observable property.
* @signature `observe.compute(attrName)`
* @param {String} attrName the property to bind to
* @return {can.compute} a [can.compute] bound to _attrName_
*
* @body
* `compute` is a convenience method for making computes from properties
* of Observes. More information about computes can be found under [can.compute].
*
* @codestart
* var observe = new can.Observe({a: 'Alexis'});
* var name = observe.compute('a');
* name.bind('change', function(ev, nevVal, oldVal) {
* console.log('a changed from ' + oldVal + 'to' + newName + '.');
* });
*
* name(); // 'Alexis'
*
* observe.attr('a', 'Adam'); // 'a changed from Alexis to Adam.'
* name(); // 'Adam'
*
* name('Alice'); // 'a changed from Adam to Alice.'
* name(); // 'Alice'
*/
compute: function(prop) {
return can.compute(this,prop);
}
});
// Helpers for `observable` lists.
var splice = [].splice,
/**
* @constructor can.Observe.List
* @inherits can.Observe
* @download can/observe
* @test can/observe/qunit.html
* @parent canjs
*