sproutcore / core.js
100644 898 lines (736 sloc) 29.698 kb
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
// ==========================================================================
// SproutCore
// Author: Charles Jolley
// copyright 2006-2008, Sprout Systems, Inc.
// ==========================================================================
 
/*global $type, $I, $A, NodeList */
 
// this is used by the JavascriptCompile class on the server side. You can
// use this to automatically determine the order javascript files need to be
// included in. On the client side, this is a NOP.
var require = require || function require() { } ;
require('license') ;
 
// ........................................
// GLOBAL CONSTANTS
//
// Most global constants should be defined inside of the SC namespace.
// However the following two are useful enough and generally benign enough
// to put into the global object.
var YES = true ;
var NO = false ;
 
// prevent a console.log from blowing things up if we are on a browser that
// does not support it
if (typeof console === 'undefined') {
  var console = console || window.console || {} ;
  console.log = console.info = console.warn = console.error = function(){};
}
 
// ........................................
// BOOTSTRAP
//
// The root namespace and some common utility methods are defined here. The
// rest of the methods go into the mixin defined below.
 
/**
@namespace
The SproutCore namespace. All SproutCore methods and functions are defined
inside of this namespace. You generally should not add new properties to
this namespace as it may be overwritten by future versions of SproutCore.
You can also use the shorthand "SC" instead of "SproutCore".
SproutCore-Base is a framework that provides core functions for SproutCore
including cross-platform functions, support for property observing and
objects. It's focus is on small size and performance. You can use this
in place of or along-side other cross-platform libraries such as jQuery or
Prototype.
The core Base framework is based on the jQuery API with a number of
performance optimizations.
*/
var SC = SC || {} ;
var SproutCore = SproutCore || SC ;
 
/**
Adds properties to a target object.
Takes the root object and adds the attributes for any additional
arguments passed.
 
@param target {Object} the target object to extend
@param properties {Object} one or more objects with properties to copy.
@returns {Object} the target object.
@static
*/
SC.mixin = function() {
  // copy reference to target object
  var target = arguments[0] || {};
  var idx = 1;
  var length = arguments.length ;
  var options ;
 
  // Handle case where we have only one item...extend SC
  if (length === 1) {
    target = this || {};
    idx=0;
  }
 
  for ( ; idx < length; idx++ ) {
    if (!(options = arguments[idx])) continue ;
    for(var key in options) {
      if (!options.hasOwnProperty(key)) continue ;
      var src = target[key];
      var copy = options[key] ;
      if (target===copy) continue ; // prevent never-ending loop
      if (copy !== undefined) target[key] = copy ;
    }
  }
  
  return target;
} ;
 
/**
Alternative to mixin. Provided for compatibility with jQuery.
@function
*/
SC.extend = SC.mixin ;
 
 
// Enough with the bootstrap code. Let's define some core functions
SC.mixin(/** @scope SC */ {
  
  // ........................................
  // GLOBAL CONSTANTS
  //
  T_ERROR: 'error',
  T_OBJECT: 'object',
  T_NULL: 'null',
  T_CLASS: 'class',
  T_HASH: 'hash',
  T_FUNCTION: 'function',
  T_UNDEFINED: 'undefined',
  T_NUMBER: 'number',
  T_BOOL: 'boolean',
  T_ARRAY: 'array',
  T_STRING: 'string',
 
  // ........................................
  // CORE HELPER METHODS
  //
 
  /**
Returns a consistant type for the passed item.
Use this instead of the built-in typeOf() to get the type of an item.
It will return the same result across all browsers and includes a bit
more detail. Here is what will be returned:
| Return Value Constant | Meaning |
| SC.T_STRING | String primitive |
| SC.T_NUMBER | Number primitive |
| SC.T_BOOLEAN | Boolean primitive |
| SC.T_NULL | Null value |
| SC.T_UNDEFINED | Undefined value |
| SC.T_FUNCTION | A function |
| SC.T_ARRAY | An instance of Array |
| SC.T_CLASS | A SproutCore class (created using SC.Object.extend()) |
| SC.T_OBJECT | A SproutCore object instance |
| SC.T_HASH | A JavaScript object not inheriting from SC.Object |
@param item {Object} the item to check
@returns {String} the type
*/
  typeOf: function(item) {
    if (item === undefined) return SC.T_UNDEFINED ;
    if (item === null) return SC.T_NULL ;
    var ret = typeof(item) ;
    if (ret == "object") {
      if (item instanceof Array) {
        ret = SC.T_ARRAY ;
      } else if (item instanceof Function) {
        ret = item.isClass ? SC.T_CLASS : SC.T_FUNCTION ;
        
      // NB: typeOf() may be called before SC.Error has had a chance to load
      // so this code checks for the presence of SC.Error first just to make
      // sure. No error instance can exist before the class loads anyway so
      // this is safe.
      } else if (SC.Error && (item instanceof SC.Error)) {
        ret = SC.T_ERROR ;
      } else if (item.isObject === true) {
        ret = SC.T_OBJECT ;
      } else ret = SC.T_HASH ;
    } else if (ret === SC.T_FUNCTION) ret = (item.isClass) ? SC.T_CLASS : SC.T_FUNCTION;
    return ret ;
  },
  
  /**
Returns YES if the passed value is null or undefined. This avoids errors
from JSLint complaining about use of ==, which can be technically
confusing.
*/
  none: function(obj) {
    return obj===null || obj===undefined;
  },
  
  /**
Returns YES if the passed object is an array or array-like.
Unlike SC.$type this method returns true even if the passed object is
not formally array but appears to be array-like (i.e. has a length
property, responds to .objectAt, etc.)
@param obj {Object} the object to test
@returns {Boolean}
*/
  isArray: function(obj) {
    var len = (obj ? obj.length : null), type = SC.typeOf(obj);
    return !(SC.none(len) ||
      ((type === SC.T_FUNCTION) && !(obj instanceof NodeList)) ||
      (type === SC.T_STRING) || obj.setInterval) || (obj && obj.objectAt) ;
  },
  
  /**
Makes an object into an Array if it is not array or array-like already.
Unlike SC.$A(), this method will not clone the object if it is already
an array.
*/
  makeArray: function(obj) {
    return SC.isArray(obj) ? obj : SC.$A(obj);
  },
  
  /**
Converts the passed object to an Array. If the object appears to be
array-like, a new array will be cloned from it. Otherwise, a new array
will be created with the item itself as the only item in the array.
@param object {Object} any enumerable or array-like object.
@returns {Array} Array of items
*/
  $A: function(obj) {
    
    // null or undefined -- fast path
    if (SC.none(obj)) return [] ;
    
    // primitive -- fast path
    if (obj.slice instanceof Function) return obj.slice() ;
    
    // enumerable -- fast path
    if (obj.toArray) return obj.toArray() ;
 
    // if not array-like, then just wrap in array.
    if (!SC.isArray(obj)) return [obj];
 
    // when all else fails, do a manual convert...
    var ret = [], len = obj.length;
    while(--len >= 0) ret[len] = obj[len];
    return ret ;
  },
 
  guidKey: "_sc_guid_" + new Date().getTime(),
  
  /**
Returns a unique GUID for the object. If the object does not yet have
a guid, one will be assigned to it. You can call this on any object,
SC.Object-based or not, but be aware that it will add a _guid property.
You can also use this method on DOM Element objects.
@param obj {Object} any object, string, number, Element, or primitive
@returns {String} the unique guid for this instance.
*/
  guidFor: function(obj) {
    if (obj === undefined) return "(undefined)" ;
    if (obj === null) return '(null)' ;
    var guidKey = this.guidKey ;
    if (obj[guidKey]) return obj[guidKey] ;
    
    switch(SC.$type(obj)) {
      case SC.T_NUMBER:
        return (this._numberGuids[obj] = this._numberGuids[obj] || ("#" + obj));
      case SC.T_STRING:
        return (this._stringGuids[obj] = this._stringGuids[obj] || ("$" + obj));
      case SC.T_BOOL:
        return (obj) ? "(true)" : "(false)" ;
      default:
        return SC.generateGuid(obj);
    }
  },
  
  /**
Returns the cachekey for the named key + prefix. Uses a cache internally
for performance.
*/
  keyFor: function() {
    var cache = {};
    return function keyFor(prefix, key) {
      var ret, pcache = cache[prefix];
      if (!pcache) pcache = cache[prefix] = {}; // get cache for prefix
      ret = pcache[key];
      if (!ret) ret = pcache[key] = prefix + "_" + key ;
      return ret ;
    } ;
  }(),
  
  /**
Generates a new guid, optionally saving the guid to the object that you
pass in. You will rarely need to use this method. Instead you should
call SC.guidFor(obj), which return an existing guid if available.
@param {Object} obj the object to assign the guid to
@returns {String} the guid
*/
  generateGuid: function(obj) {
    var ret = ("@" + (SC._nextGUID++));
    if (obj) obj[SC.guidKey] = ret ;
    return ret ;
  },
  
  _nextGUID: 0, _numberGuids: [], _stringGuids: {},
 
  /**
Returns a unique hash code for the object. If the object implements
a hash() method, the value of that method will be returned. Otherwise,
this will return the same value as guidFor().
Unlike guidFor(), this method allows you to implement logic in your
code to cause two separate instances of the same object to be treated as
if they were equal for comparisons and other functions.
IMPORTANT: If you implement a hash() method, it MUST NOT return a number
or a string that contains only a number. Typically hash codes are strings
that begin with a "%".
@param obj {Object} the object
@returns {String} the hash code for this instance.
*/
  hashFor: function(obj) {
    return (obj && obj.hash && SC.$type(obj.hash) === SC.T_FUNCTION) ? obj.hash() : this.guidFor(obj) ;
  },
 
  /**
This will compare the two object values using their hash codes.
@param a {Object} first value to compare
@param b {Object} the second value to compare
@returns {Boolean} YES if the two have equal hash code values.
*/
  isEqual: function(a,b) {
    // shortcut a few places.
    if (a === null) {
      return b === null ;
    } else if (a === undefined) {
      return b === undefined ;
    
    // finally, check their hash-codes
    } else return SC.hashFor(a) === SC.hashFor(b) ;
  },
 
  _numberGuids: [],
  
  _stringGuids: {},
  
  /**
Empty function. Useful for some operations.
*/
  K: function() { return this; },
  
  /** Empty array. Useful for some optimizations. */
  A: [],
  
  /**
Creates a new object with the passed object as its prototype.
This method uses JavaScript's native inheritence method to create a new
object.
You cannot use beget() to create new SC.Object-based objects, but you
can use it to beget Arrays, Hashes, Sets and objects you build yourself.
Note that when you beget() a new object, this method will also call the
didBeget() method on the object you passed in if it is defined. You can
use this method to perform any other setup needed.
In general, you will not use beget() often as SC.Object is much more
useful, but for certain rare algorithms, this method can be very useful.
For more information on using beget(), see the section on beget() in
Crockford's JavaScript: The Good Parts.
@param obj {Object} the object to beget
@returns {Object} the new object.
*/
  beget: function(obj) {
    if (SC.none(obj)) return null ;
    var K = SC.K; K.prototype = obj ;
    var ret = new K();
    K.prototype = null ; // avoid leaks
    if (SC.$type(obj.didBeget) === SC.T_FUNCTION) ret = obj.didBeget(ret);
    return ret ;
  },
  
  /**
Creates a clone of the passed object. This function can take just about
any type of object and create a clone of it, including primitive values
(which are not actually cloned because they are immutable).
If the passed object implements the clone() method, then this function
will simply call that method and return the result.
@param object {Object} the object to clone
@returns {Object} the cloned object
*/
  clone: function(object) {
    var ret = object ;
    switch (SC.typeOf(object)) {
    case SC.T_ARRAY:
      if (object.clone && SC.typeOf(object.clone) === SC.T_FUNCTION) {
        ret = object.clone() ;
      } else ret = object.slice() ;
      break ;
    
    case SC.T_HASH:
    case SC.T_OBJECT:
      if (object.clone && SC.typeOf(object.clone) === SC.T_FUNCTION) {
        ret = object.clone() ;
      } else {
        ret = {} ;
        for(var key in object) ret[key] = object[key] ;
      }
    }
    
    return ret ;
  },
  
  /**
Returns a new object combining the values of all passed hashes.
@param object {Object} one or more objects
@returns {Object} new Object
*/
  merge: function() {
    var ret = {}, len = arguments.length, idx;
    for(idx=0;idx<len;idx++) SC.mixin(ret, arguments[idx]);
    return ret ;
  },
  
  /**
Returns all of the keys defined on an object or hash. This is useful
when inspecting objects for debugging.
@param {Object} obj
@returns {Array} array of keys
*/
  keys: function(obj) {
    var ret = [];
    for(var key in obj) ret.push(key);
    return ret;
  },
  
  /**
Convenience method to inspect an object. This method will attempt to
convert the object into a useful string description.
*/
  inspect: function(obj) {
    var v, ret = [] ;
    for(var key in obj) {
      v = obj[key] ;
      if (v === 'toString') continue ; // ignore useless items
      if (SC.typeOf(v) === SC.T_FUNCTION) v = "function() { ... }" ;
      ret.push(key + ": " + v) ;
    }
    return "{" + ret.join(" , ") + "}" ;
  },
 
  /**
Returns a tuple containing the object and key for the specified property
path. If no object could be found to match the property path, then
returns null.
This is the standard method used throughout SproutCore to resolve property
paths.
@param path {String} the property path
@param root {Object} optional parameter specifying the place to start
@returns {Array} array with [object, property] if found or null
*/
  tupleForPropertyPath: function(path, root) {
    
    // if the passed path is itself a tuple, return it
    if (SC.$type(path) === SC.T_ARRAY) return path ;
 
    // find the key. It is the last . or first *
    var key ;
    var stopAt = path.indexOf('*') ;
    if (stopAt < 0) stopAt = path.lastIndexOf('.') ;
    key = (stopAt >= 0) ? path.slice(stopAt+1) : path ;
    
    // convert path to object.
    var obj = this.objectForPropertyPath(path, root, stopAt) ;
    return (obj && key) ? [obj,key] : null ;
  },
 
  /**
Finds the object for the passed path or array of path components. This is
the standard method used in SproutCore to traverse object paths.
@param path {String} the path
@param root {Object} optional root object. window is used otherwise
@param stopAt {Integer} optional point to stop searching the path.
@returns {Object} the found object or undefined.
*/
  objectForPropertyPath: function(path, root, stopAt) {
 
    var loc, nextDotAt, key, max ;
    
    if (!root) root = window ;
    
    // faster method for strings
    if (SC.$type(path) === SC.T_STRING) {
      if (stopAt === undefined) stopAt = path.length ;
      loc = 0 ;
      while((root) && (loc < stopAt)) {
        nextDotAt = path.indexOf('.', loc) ;
        if ((nextDotAt < 0) || (nextDotAt > stopAt)) nextDotAt = stopAt;
        key = path.slice(loc, nextDotAt);
        root = root.get ? root.get(key) : root[key] ;
        loc = nextDotAt+1;
      }
      if (loc < stopAt) root = undefined; // hit a dead end. :(
        
    // older method using an array
    } else {
 
      loc = 0; max = path.length; key = null;
      while((loc < max) && root) {
        key = path[loc++];
        if (key) root = (root.get) ? root.get(key) : root[key] ;
      }
      if (loc < max) root = undefined ;
    }
    
    return root ;
  },
  
  /**
This function will restore the few global functions defined by SproutCore
to their original values. You can call this method if the globals
defined by SproutCore conflict with another library you are using. The
current global methods restored by this method are:
- $type()
- $I()
@returns {SC} SproutCore namespace
*/
  noConflict: function() {
    $type = SC._originalGlobals.$type ;
    $I = SC._originalGlobals.$I ;
    $A = SC._originalGlobals.$A ;
  },
  
  /**
Reads or writes data from a global cache. You can use this facility to
store information about an object without actually adding properties to
the object itself. This is needed especially when working with DOM,
which can leak easily in IE.
To read data, simply pass in the reference element (used as a key) and
the name of the value to read. To write, also include the data.
You can also just pass an object to retrieve the entire cache.
@param elem {Object} An object or Element to use as scope
@param name {String} Optional name of the value to read/write
@param data {Object} Optional data. If passed, write.
@returns {Object} the value of the named data
*/
  data: function(elem, name, data) {
    elem = (elem === window) ? "@window" : elem ;
    var hash = SC.hashFor(elem) ; // get the hash key
    
    // Generate the data cache if needed
    var cache = SC._data_cache ;
    if (!cache) SC._data_cache = cache = {} ;
    
    // Now get cache for element
    var elemCache = cache[hash] ;
    if (name && !elemCache) cache[hash] = elemCache = {} ;
    
    // Write data if provided
    if (elemCache && (data !== undefined)) elemCache[name] = data ;
    
    return (name) ? elemCache[name] : elemCache ;
  },
  
  /**
Removes data from the global cache. This is used throughout the
framework to hold data without creating memory leaks.
You can remove either a single item on the cache or all of the cached
data for an object.
@param elem {Object} An object or Element to use as scope
@param name {String} optional name to remove.
@returns {Object} the value or cache that was removed
*/
  removeData: function(elem, name) {
    elem = (elem === window) ? "@window" : elem ;
    var hash = SC.hashFor(elem) ;
    
    // return undefined if no cache is defined
    var cache = SC._data_cache ;
    if (!cache) return undefined ;
    
    // return undefined if the elem cache is undefined
    var elemCache = cache[hash] ;
    if (!elemCache) return undefined;
    
    // get the return value
    var ret = (name) ? elemCache[name] : elemCache ;
    
    // and delete as appropriate
    if (name) {
      delete elemCache[name] ;
    } else {
      delete cache[hash] ;
    }
    
    return ret ;
  },
  
  /**
Create or update a SproutCore namespace. If you also pass a constructor
function, this function will be called with the new namespace object as
the first parameter so you can set it up within a private closure.
If a namespace does not already exist, this method will create it.
Otherwise, it will work with the existing namespace. A namespace is
simply a SproutCore object instance.
@param name {String} name of namespace
@param op {Function|Hash} applied to namespace.
@returns {SC.Object} the namespace
*/
  namespace: function(name, op) {
    // walk path to find or create...
    var obj, loc = 0, len = name.length, next, key, root = window;
    while(loc<len) {
      next = name.indexOf('.');
      if (next < 0) next = len ;
      key = name.slice(loc, next);
      obj = root[key];
      if (!obj) obj = root[key] = SC.Object.create();
      loc = next+1;
    }
    
    // obj now containts the namespace. If a function was passed, execute it
    // if a hash was passed, copy its properties.
    switch(SC.typeOf(op)) {
      case SC.T_FUNCTION:
        op(obj);
        break;
      case SC.T_HASH:
        SC.mixin(obj, op);
        break;
      default:
        // do nothing;
    }
    
    // and return obj
    return obj;
  }
  
});
 
/** Alias for SC.typeOf() */
SC.$type = SC.typeOf ;
  
/** @private Provided for compatibility with old HTML templates. */
SC.didLoad = SC.K ;
 
// ........................................
// GLOBAL EXPORTS
//
// These can be restored using SC.restoreGlobals();
var $type, $I, $A ;
SC._originalGlobals = { $type: $type, $I: $I, $A: $A } ;
$type = SC.typeOf;
$I = SC.inspect ;
$A = SC.$A ;
 
// ........................................
// FUNCTION ENHANCEMENTS
//
// Enhance function.
SC.mixin(Function.prototype,
/** @scope Function.prototype */ {
  
  /**
Indicates that the function should be treated as a computed property.
Computed properties are methods that you want to treat as if they were
static properties. When you use get() or set() on a computed property,
the object will call the property method and return its value instead of
returning the method itself. This makes it easy to create "virtual
properties" that are computed dynamically from other properties.
Consider the following example:
{{{
contact = SC.Object.create({
 
firstName: "Charles",
lastName: "Jolley",
// This is a computed property!
fullName: function() {
return this.getEach('firstName','lastName').compact().join(' ') ;
}.property('firstName', 'lastName'),
// this is not
getFullName: function() {
return this.getEach('firstName','lastName').compact().join(' ') ;
}
});
 
contact.get('firstName') ;
--> "Charles"
contact.get('fullName') ;
--> "Charles Jolley"
contact.get('getFullName') ;
--> function()
}}}
Note that when you get the fullName property, SproutCore will call the
fullName() function and return its value whereas when you get() a property
that contains a regular method (such as getFullName above), then the
function itself will be returned instead.
h2. Using Dependent Keys
 
Computed properties are often computed dynamically from other member
properties. Whenever those properties change, you need to notify any
object that is observing the computed property that the computed property
has changed also. We call these properties the computed property is based
upon "dependent keys".
For example, in the contact object above, the fullName property depends on
the firstName and lastName property. If either property value changes,
any observer watching the fullName property will need to be notified as
well.
You inform SproutCore of these dependent keys by passing the key names
as parameters to the property() function. Whenever the value of any key
you name here changes, the computed property will be marked as changed
also.
You should always register dependent keys for computed properties to
ensure they update.
h2. Using Computed Properties as Setters
Computed properties can be used to modify the state of an object as well
as to return a value. Unlike many other key-value system, you use the
same method to both get and set values on a computed property. To
write a setter, simply declare two extra parameters: key and value.
Whenever your property function is called as a setter, the value
parameter will be set. Whenever your property is called as a getter the
value parameter will be undefined.
For example, the following object will split any full name that you set
into a first name and last name components and save them.
{{{
contact = SC.Object.create({
fullName: function(key, value) {
if (value !== undefined) {
var parts = value.split(' ') ;
this.beginPropertyChanges()
.set('firstName', parts[0])
.set('lastName', parts[1])
.endPropertyChanges() ;
}
return this.getEach('firstName', 'lastName').compact().join(' ');
}.property('firstName','lastName')
}) ;
}}}
bq. *Why Use The Same Method for Getters and Setters?* Most property-
based frameworks expect you to write two methods for each property but
SproutCore only uses one. We do this because most of the time when
you write a setter is is basically a getter plus some extra work. There
is little added benefit in writing both methods when you can conditionally
exclude part of it. This helps to keep your code more compact and easier
to maintain.
@param dependentKeys {String...} optional set of dependent keys
@returns {Function} the declared function instance
*/
  property: function() {
    this.dependentKeys = SC.$A(arguments) ;
    this.cacheKey = "__cache__" + SC.guidFor(this) ;
    this.lastSetValueKey = "__lastValue__" + SC.guidFor(this) ;
    this.isProperty = true; return this;
  },
  
  /**
You can call this method on a computed property to indicate that the
property is cacheable (or not cacheable). By default all computed
properties are not cached. Enabling this feature will allow SproutCore
to cache the return value of your computed property and to use that
value until one of your dependent properties changes or until you
invoke propertyDidChange() and name the computed property itself.
If you do not specify this option, computed properties are assumed to be
not cacheable.
@param {Boolean} aFlag optionally indicate cacheable or no, default YES
@returns {Function} reciever
*/
  cacheable: function(aFlag) {
    this.isProperty = YES; // also make a property just in case
    if (!this.dependentKeys) this.dependentKeys = [] ;
    this.isCacheable = (aFlag === undefined) ? YES : aFlag ;
    return this;
  },
  
  /**
Makes the computed property as an outlet. Outlets can be setup en-masse
when the object is first instantiated by calling initOutlets(). (This
method is defined in SC.Observable).
*/
  outlet: function(aFlag) {
    this.autoconfiguredOutlet = (aFlag === undefined) ? YES : aFlag;
    return this ;
  },
  
  /**
Indicates that the computed property is volatile. Normally SproutCore
assumes that your computed property is indempotent. That is, calling
set() on your property more than once with the same value has the same
effect as calling it only once.
All non-computed properties are indempotent and normally you should make
your computed properties behave the same way. However, if you need to
make your property change its return value everytime your method is
called, you may chain this to your property to make it volatile.
If you do not specify this option, properties are assumed to be
non-volatile.
@param {Boolean} aFlag optionally indicate state, default to YES
@returns {Function} receiver
*/
  indempotent: function(aFlag) {
    this.isProperty = YES; // also make a property just in case
    if (!this.dependentKeys) this.dependentKeys = [] ;
    this.isVolatile = !((aFlag === undefined) ? NO : aFlag) ;
    return this;
  },
  
  /**
Declare that a function should observe an object at the named path. Note
that the path is used only to construct the observation one time.
*/
  observes: function(propertyPaths) {
    
    // sort property paths into local paths (i.e just a property name) and
    // full paths (i.e. those with a . or * in them)
    var loc = arguments.length, local = null, paths = null;
    while(--loc >= 0) {
      var path = arguments[loc] ;
      // local
      if ((path.indexOf('.')<0) && (path.indexOf('*')<0)) {
        if (!local) local = this.localPropertyPaths = [];
        local.push(path);
        
      // regular
      } else {
        if (!paths) paths = this.propertyPaths = [];
        paths.push(path) ;
      }
    }
    return this;
  },
  
  typeConverter: function() {
    this.isTypeConverter = true; return this ;
  },
  
  /**
Creates a timer that will execute the function after a specified
period of time.
If you pass an optional set of arguments, the arguments will be passed
to the function as well. Otherwise the function should have the
signature:
{{{
function functionName(timer)
}}}
 
@param target {Object} optional target object to use as this
@param interval {Number} the time to wait, in msec
@returns {SC.Timer} scheduled timer
*/
  invokeLater: function(target, interval) {
    if (interval === undefined) interval = 1 ;
    var f = this;
    if (arguments.length > 2) {
      var args = SC.$A(arguments).slice(2,arguments.length);
      args.unshift(target);
      f = f.bind.apply(f, args) ;
    }
    return SC.Timer.schedule({ target: target, action: f, interval: interval });
  }
  
}) ;