forked from airhorns/batman
/
batman.coffee
5135 lines (4326 loc) · 169 KB
/
batman.coffee
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
#
# batman.js
#
# Created by Nick Small
# Copyright 2011, Shopify
#
# The global namespace, the `Batman` function will also create also create a new
# instance of Batman.Object and mixin all arguments to it.
Batman = (mixins...) ->
new Batman.Object mixins...
Batman.version = '0.8.0'
Batman.config =
pathPrefix: '/'
usePushState: no
# Global Helpers
# -------
# `$typeOf` returns a string that contains the built-in class of an object
# like `String`, `Array`, or `Object`. Note that only `Object` will be returned for
# the entire prototype chain.
Batman.typeOf = $typeOf = (object) ->
return "Undefined" if typeof object == 'undefined'
_objectToString.call(object).slice(8, -1)
# Cache this function to skip property lookups.
_objectToString = Object.prototype.toString
# `$mixin` applies every key from every argument after the first to the
# first argument. If a mixin has an `initialize` method, it will be called in
# the context of the `to` object, and it's key/values won't be applied.
Batman.mixin = $mixin = (to, mixins...) ->
hasSet = typeof to.set is 'function'
for mixin in mixins
continue if $typeOf(mixin) isnt 'Object'
for own key, value of mixin
continue if key in ['initialize', 'uninitialize', 'prototype']
if hasSet
to.set(key, value)
else if to.nodeName?
Batman.data to, key, value
else
to[key] = value
if typeof mixin.initialize is 'function'
mixin.initialize.call to
to
# `$unmixin` removes every key/value from every argument after the first
# from the first argument. If a mixin has a `deinitialize` method, it will be
# called in the context of the `from` object and won't be removed.
Batman.unmixin = $unmixin = (from, mixins...) ->
for mixin in mixins
for key of mixin
continue if key in ['initialize', 'uninitialize']
delete from[key]
if typeof mixin.uninitialize is 'function'
mixin.uninitialize.call from
from
# `$functionName` returns the name of a given function, if any
# Used to deal with functions not having the `name` property in IE
Batman._functionName = $functionName = (f) ->
return f.__name__ if f.__name__
return f.name if f.name
f.toString().match(/\W*function\s+([\w\$]+)\(/)?[1]
# `$preventDefault` checks for preventDefault, since it's not
# always available across all browsers
Batman._preventDefault = $preventDefault = (e) ->
if typeof e.preventDefault is "function" then e.preventDefault() else e.returnValue = false
Batman._isChildOf = $isChildOf = (parentNode, childNode) ->
node = childNode.parentNode
while node
return true if node == parentNode
node = node.parentNode
false
$setImmediate = $clearImmediate = null
_implementImmediates = (container) ->
canUsePostMessage = ->
return false unless container.postMessage
async = true
oldMessage = container.onmessage
container.onmessage = -> async = false
container.postMessage("","*")
container.onmessage = oldMessage
async
tasks = new Batman.SimpleHash
count = 0
getHandle = -> "go#{++count}"
if container.setImmediate
$setImmediate = container.setImmediate
$clearImmediate = container.clearImmediate
else if container.msSetImmediate
$setImmediate = msSetImmediate
$clearImmediate = msClearImmediate
else if canUsePostMessage()
prefix = 'com.batman.'
functions = new Batman.SimpleHash
handler = (e) ->
return unless ~e.data.search(prefix)
handle = e.data.substring(prefix.length)
tasks.unset(handle)?()
if container.addEventListener
container.addEventListener('message', handler, false)
else
container.attachEvent('onmessage', handler)
$setImmediate = (f) ->
tasks.set(handle = getHandle(), f)
container.postMessage(prefix+handle, "*")
handle
$clearImmediate = (handle) -> tasks.unset(handle)
else if typeof document isnt 'undefined' && "onreadystatechange" in document.createElement("script")
$setImmediate = (f) ->
handle = getHandle()
script = document.createElement("script")
script.onreadystatechange = ->
tasks.get(handle)?()
script.onreadystatechange = null
script.parentNode.removeChild(script)
script = null
document.documentElement.appendChild(script)
handle
$clearImmediate = (handle) -> tasks.unset(handle)
else
$setImmediate = (f) -> setTimeout(f, 0)
$clearImmediate = (handle) -> clearTimeout(handle)
Batman.setImmediate = $setImmediate
Batman.clearImmediate = $clearImmediate
Batman.setImmediate = $setImmediate = ->
_implementImmediates(Batman.container)
Batman.setImmediate.apply(@, arguments)
Batman.clearImmediate = $clearImmediate = ->
_implementImmediates(Batman.container)
Batman.clearImmediate.apply(@, arguments)
Batman.forEach = $forEach = (container, iterator, ctx) ->
if container.forEach
container.forEach(iterator, ctx)
else if container.indexOf
iterator.call(ctx, e, i, container) for e,i in container
else
iterator.call(ctx, k, v, container) for k,v of container
Batman.objectHasKey = $objectHasKey = (object, key) ->
if typeof object.hasKey is 'function'
object.hasKey(key)
else
key of object
Batman.contains = $contains = (container, item) ->
if container.indexOf
item in container
else if typeof container.has is 'function'
container.has(item)
else
$objectHasKey(container, item)
Batman.get = $get = (base, key) ->
if typeof base.get is 'function'
base.get(key)
else
Batman.Property.forBaseAndKey(base, key).getValue()
# `translate` is hook for the i18n extra to override and implemnent. All strings which might
# be shown to the user pass through this method. `translate` is aliased to `t` internally.
Batman.translate = (x, values = {}) -> helpers.interpolate($get(Batman.translate.messages, x), values)
Batman.translate.messages = {}
t = -> Batman.translate(arguments...)
# Developer Tooling
# -----------------
developer =
suppressed: false
DevelopmentError: (->
DevelopmentError = (@message) ->
@name = "DevelopmentError"
DevelopmentError:: = Error::
DevelopmentError
)()
_ie_console: (f, args) ->
console?[f] "...#{f} of #{args.length} items..." unless args.length == 1
console?[f] arg for arg in args
suppress: (f) ->
developer.suppressed = true
if f
f()
developer.suppressed = false
unsuppress: ->
developer.suppressed = false
log: ->
return if developer.suppressed or !(console?.log?)
if console.log.apply then console.log(arguments...) else developer._ie_console "log", arguments
warn: ->
return if developer.suppressed or !(console?.warn?)
if console.warn.apply then console.warn(arguments...) else developer._ie_console "warn", arguments
error: (message) -> throw new developer.DevelopmentError(message)
assert: (result, message) -> developer.error(message) unless result
do: (f) -> f() unless developer.suppressed
addFilters: ->
$mixin Batman.Filters,
log: (value, key) ->
console?.log? arguments
value
logStack: (value) ->
console?.log? developer.currentFilterStack
value
Batman.developer = developer
developer.assert (->).bind, "Error! Batman needs Function.bind to work! Please shim it using something like es5-shim or augmentjs!"
# Helpers
# -------
# Just a few random Rails-style string helpers. You can add more
# to the Batman.helpers object.
class Batman.Inflector
plural: []
singular: []
uncountable: []
@plural: (regex, replacement) -> @::plural.unshift [regex, replacement]
@singular: (regex, replacement) -> @::singular.unshift [regex, replacement]
@irregular: (singular, plural) ->
if singular.charAt(0) == plural.charAt(0)
@plural new RegExp("(#{singular.charAt(0)})#{singular.slice(1)}$", "i"), "$1" + plural.slice(1)
@plural new RegExp("(#{singular.charAt(0)})#{plural.slice(1)}$", "i"), "$1" + plural.slice(1)
@singular new RegExp("(#{plural.charAt(0)})#{plural.slice(1)}$", "i"), "$1" + singular.slice(1)
else
@plural new RegExp("#{singular}$", 'i'), plural
@plural new RegExp("#{plural}$", 'i'), plural
@singular new RegExp("#{plural}$", 'i'), singular
@uncountable: (strings...) -> @::uncountable = @::uncountable.concat(strings.map((x) -> new RegExp("#{x}$", 'i')))
@plural(/$/, 's')
@plural(/s$/i, 's')
@plural(/(ax|test)is$/i, '$1es')
@plural(/(octop|vir)us$/i, '$1i')
@plural(/(octop|vir)i$/i, '$1i')
@plural(/(alias|status)$/i, '$1es')
@plural(/(bu)s$/i, '$1ses')
@plural(/(buffal|tomat)o$/i, '$1oes')
@plural(/([ti])um$/i, '$1a')
@plural(/([ti])a$/i, '$1a')
@plural(/sis$/i, 'ses')
@plural(/(?:([^f])fe|([lr])f)$/i, '$1$2ves')
@plural(/(hive)$/i, '$1s')
@plural(/([^aeiouy]|qu)y$/i, '$1ies')
@plural(/(x|ch|ss|sh)$/i, '$1es')
@plural(/(matr|vert|ind)(?:ix|ex)$/i, '$1ices')
@plural(/([m|l])ouse$/i, '$1ice')
@plural(/([m|l])ice$/i, '$1ice')
@plural(/^(ox)$/i, '$1en')
@plural(/^(oxen)$/i, '$1')
@plural(/(quiz)$/i, '$1zes')
@singular(/s$/i, '')
@singular(/(n)ews$/i, '$1ews')
@singular(/([ti])a$/i, '$1um')
@singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '$1$2sis')
@singular(/(^analy)ses$/i, '$1sis')
@singular(/([^f])ves$/i, '$1fe')
@singular(/(hive)s$/i, '$1')
@singular(/(tive)s$/i, '$1')
@singular(/([lr])ves$/i, '$1f')
@singular(/([^aeiouy]|qu)ies$/i, '$1y')
@singular(/(s)eries$/i, '$1eries')
@singular(/(m)ovies$/i, '$1ovie')
@singular(/(x|ch|ss|sh)es$/i, '$1')
@singular(/([m|l])ice$/i, '$1ouse')
@singular(/(bus)es$/i, '$1')
@singular(/(o)es$/i, '$1')
@singular(/(shoe)s$/i, '$1')
@singular(/(cris|ax|test)es$/i, '$1is')
@singular(/(octop|vir)i$/i, '$1us')
@singular(/(alias|status)es$/i, '$1')
@singular(/^(ox)en/i, '$1')
@singular(/(vert|ind)ices$/i, '$1ex')
@singular(/(matr)ices$/i, '$1ix')
@singular(/(quiz)zes$/i, '$1')
@singular(/(database)s$/i, '$1')
@irregular('person', 'people')
@irregular('man', 'men')
@irregular('child', 'children')
@irregular('sex', 'sexes')
@irregular('move', 'moves')
@irregular('cow', 'kine')
@irregular('zombie', 'zombies')
@uncountable('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans')
ordinalize: (number) ->
absNumber = Math.abs(parseInt(number))
if absNumber % 100 in [11..13]
number + "th"
else
switch absNumber % 10
when 1
number + "st"
when 2
number + "nd"
when 3
number + "rd"
else
number + "th"
pluralize: (word) ->
for uncountableRegex in @uncountable
return word if uncountableRegex.test(word)
for [regex, replace_string] in @plural
return word.replace(regex, replace_string) if regex.test(word)
word
singularize: (word) ->
for uncountableRegex in @uncountable
return word if uncountableRegex.test(word)
for [regex, replace_string] in @singular
return word.replace(regex, replace_string) if regex.test(word)
word
camelize_rx = /(?:^|_|\-)(.)/g
capitalize_rx = /(^|\s)([a-z])/g
underscore_rx1 = /([A-Z]+)([A-Z][a-z])/g
underscore_rx2 = /([a-z\d])([A-Z])/g
helpers = Batman.helpers =
inflector: new Batman.Inflector
ordinalize: -> helpers.inflector.ordinalize.apply helpers.inflector, arguments
singularize: -> helpers.inflector.singularize.apply helpers.inflector, arguments
pluralize: (count, singular, plural) ->
if arguments.length < 2
helpers.inflector.pluralize count
else
"#{count || 0} " + if +count is 1 then singular else (plural || helpers.inflector.pluralize(singular))
camelize: (string, firstLetterLower) ->
string = string.replace camelize_rx, (str, p1) -> p1.toUpperCase()
if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string
underscore: (string) ->
string.replace(underscore_rx1, '$1_$2')
.replace(underscore_rx2, '$1_$2')
.replace('-', '_').toLowerCase()
capitalize: (string) -> string.replace capitalize_rx, (m,p1,p2) -> p1 + p2.toUpperCase()
trim: (string) -> if string then string.trim() else ""
interpolate: (stringOrObject, keys) ->
if typeof stringOrObject is 'object'
string = stringOrObject[keys.count]
unless string
string = stringOrObject['other']
else
string = stringOrObject
for key, value of keys
string = string.replace(new RegExp("%\\{#{key}\\}", "g"), value)
string
class Batman.Event
@forBaseAndKey: (base, key) ->
if base.isEventEmitter
base.event(key)
else
new Batman.Event(base, key)
constructor: (@base, @key) ->
@handlers = new Batman.SimpleSet
@_preventCount = 0
isEvent: true
isEqual: (other) ->
@constructor is other.constructor and @base is other.base and @key is other.key
hashKey: ->
@hashKey = -> key
key = "<Batman.Event base: #{Batman.Hash::hashKeyFor(@base)}, key: \"#{Batman.Hash::hashKeyFor(@key)}\">"
addHandler: (handler) ->
@handlers.add(handler)
@autofireHandler(handler) if @oneShot
this
removeHandler: (handler) ->
@handlers.remove(handler)
this
eachHandler: (iterator) ->
@handlers.forEach(iterator)
if @base?.isEventEmitter
key = @key
@base._batman.ancestors (ancestor) ->
if ancestor.isEventEmitter and ancestor.hasEvent(key)
handlers = ancestor.event(key).handlers
handlers.forEach(iterator)
handlerContext: -> @base
prevent: -> ++@_preventCount
allow: ->
--@_preventCount if @_preventCount
@_preventCount
isPrevented: -> @_preventCount > 0
autofireHandler: (handler) ->
if @_oneShotFired and @_oneShotArgs?
handler.apply(@handlerContext(), @_oneShotArgs)
resetOneShot: ->
@_oneShotFired = false
@_oneShotArgs = null
fire: ->
return false if @isPrevented() or @_oneShotFired
context = @handlerContext()
args = arguments
if @oneShot
@_oneShotFired = true
@_oneShotArgs = arguments
@eachHandler (handler) -> handler.apply(context, args)
allowAndFire: ->
@allow()
@fire(arguments...)
Batman.EventEmitter =
isEventEmitter: true
hasEvent: (key) ->
@_batman?.get?('events')?.hasKey(key)
event: (key) ->
Batman.initializeObject @
eventClass = @eventClass or Batman.Event
events = @_batman.events ||= new Batman.SimpleHash
if events.hasKey(key)
existingEvent = events.get(key)
else
existingEvents = @_batman.get('events')
newEvent = events.set(key, new eventClass(this, key))
newEvent.oneShot = existingEvents?.get(key)?.oneShot
newEvent
on: (key, handler) ->
@event(key).addHandler(handler)
registerAsMutableSource: ->
Batman.Property.registerSource(@)
mutation: (wrappedFunction) ->
->
result = wrappedFunction.apply(this, arguments)
@event('change').fire(this, this)
result
prevent: (key) ->
@event(key).prevent()
@
allow: (key) ->
@event(key).allow()
@
isPrevented: (key) ->
@event(key).isPrevented()
fire: (key, args...) ->
@event(key).fire(args...)
allowAndFire: (key, args...) ->
@event(key).allowAndFire(args...)
class Batman.PropertyEvent extends Batman.Event
eachHandler: (iterator) -> @base.eachObserver(iterator)
handlerContext: -> @base.base
class Batman.Property
$mixin @prototype, Batman.EventEmitter
@_sourceTrackerStack: []
@sourceTracker: -> (stack = @_sourceTrackerStack)[stack.length - 1]
@defaultAccessor:
get: (key) -> @[key]
set: (key, val) -> @[key] = val
unset: (key) -> x = @[key]; delete @[key]; x
cachable: no
@forBaseAndKey: (base, key) ->
if base.isObservable
base.property(key)
else
new Batman.Keypath(base, key)
@withoutTracking: (block) ->
@pushDummySourceTracker()
try
block()
finally
@popSourceTracker()
@registerSource: (obj) ->
return unless obj.isEventEmitter
@sourceTracker()?.add(obj)
@pushSourceTracker: -> Batman.Property._sourceTrackerStack.push(new Batman.SimpleSet)
@pushDummySourceTracker: -> Batman.Property._sourceTrackerStack.push(null)
@popSourceTracker: -> Batman.Property._sourceTrackerStack.pop()
constructor: (@base, @key) ->
developer.do =>
keyType = $typeOf(@key)
if keyType in ['Array', 'Object']
developer.log "Accessing a property with an #{keyType} key. This is okay, but could be a source of memory leaks if you aren't careful."
_isolationCount: 0
cached: no
value: null
sources: null
isProperty: true
isDead: false
eventClass: Batman.PropertyEvent
isEqual: (other) ->
@constructor is other.constructor and @base is other.base and @key is other.key
hashKey: ->
@hashKey = -> key
key = "<Batman.Property base: #{Batman.Hash::hashKeyFor(@base)}, key: \"#{Batman.Hash::hashKeyFor(@key)}\">"
changeEvent: ->
event = @event('change')
@changeEvent = -> event
event
accessor: ->
keyAccessors = @base._batman?.get('keyAccessors')
accessor = if keyAccessors && (val = keyAccessors.get(@key))
val
else
@base._batman?.getFirst('defaultAccessor') or Batman.Property.defaultAccessor
@accessor = -> accessor
accessor
eachObserver: (iterator) ->
key = @key
@changeEvent().handlers.forEach(iterator)
if @base.isObservable
@base._batman.ancestors (ancestor) ->
if ancestor.isObservable and ancestor.hasProperty(key)
property = ancestor.property(key)
handlers = property.changeEvent().handlers
handlers.forEach(iterator)
observers: ->
results = []
@eachObserver (observer) -> results.push(observer)
results
hasObservers: -> @observers().length > 0
updateSourcesFromTracker: ->
newSources = @constructor.popSourceTracker()
handler = @sourceChangeHandler()
@_eachSourceChangeEvent (e) -> e.removeHandler(handler)
@sources = newSources
@_eachSourceChangeEvent (e) -> e.addHandler(handler)
_eachSourceChangeEvent: (iterator) ->
return unless @sources?
@sources.forEach (source) -> iterator(source.event('change'))
getValue: ->
@registerAsMutableSource()
unless @isCached()
@constructor.pushSourceTracker()
try
@value = @valueFromAccessor()
@cached = yes
finally
@updateSourcesFromTracker()
@value
isCachable: ->
return true if @isFinal()
cachable = @accessor().cachable
if cachable? then !!cachable else true
isCached: -> @isCachable() and @cached
isFinal: -> !!@accessor()['final']
refresh: ->
@cached = no
previousValue = @value
value = @getValue()
if value isnt previousValue and not @isIsolated()
@fire(value, previousValue)
@lockValue() if @value isnt undefined and @isFinal()
sourceChangeHandler: ->
handler = => @_handleSourceChange()
@sourceChangeHandler = -> handler
handler
_handleSourceChange: ->
if @isIsolated()
@_needsRefresh = yes
else if not @isFinal() && not @hasObservers()
@cached = no
else
@refresh()
valueFromAccessor: -> @accessor().get?.call(@base, @key)
setValue: (val) ->
return unless set = @accessor().set
@_changeValue -> set.call(@base, @key, val)
unsetValue: ->
return unless unset = @accessor().unset
@_changeValue -> unset.call(@base, @key)
_changeValue: (block) ->
@cached = no
@constructor.pushDummySourceTracker()
try
result = block.apply(this)
@refresh()
finally
@constructor.popSourceTracker()
@die() unless @isCached() or @hasObservers()
result
forget: (handler) ->
if handler?
@changeEvent().removeHandler(handler)
else
@changeEvent().handlers.clear()
observeAndFire: (handler) ->
@observe(handler)
handler.call(@base, @value, @value)
observe: (handler) ->
@changeEvent().addHandler(handler)
@getValue() unless @sources?
this
_removeHandlers: ->
handler = @sourceChangeHandler()
@_eachSourceChangeEvent (e) -> e.removeHandler(handler)
delete @sources
@changeEvent().handlers.clear()
lockValue: ->
@_removeHandlers()
@getValue = -> @value
@setValue = @unsetValue = @refresh = @observe = ->
die: ->
@_removeHandlers()
@base._batman?.properties?.unset(@key)
@isDead = true
fire: -> @changeEvent().fire(arguments...)
isolate: ->
if @_isolationCount is 0
@_preIsolationValue = @getValue()
@_isolationCount++
expose: ->
if @_isolationCount is 1
@_isolationCount--
if @_needsRefresh
@value = @_preIsolationValue
@refresh()
else if @value isnt @_preIsolationValue
@fire(@value, @_preIsolationValue)
@_preIsolationValue = null
else if @_isolationCount > 0
@_isolationCount--
isIsolated: -> @_isolationCount > 0
# Keypaths
# --------
class Batman.Keypath extends Batman.Property
constructor: (base, key) ->
if $typeOf(key) is 'String'
@segments = key.split('.')
@depth = @segments.length
else
@segments = [key]
@depth = 1
super
slice: (begin, end=@depth) ->
base = @base
for segment in @segments.slice(0, begin)
return unless base? and base = $get(base, segment)
propertyClass = base.propertyClass or Batman.Keypath
remainingSegments = @segments.slice(begin, end)
remainingPath = remainingSegments.join('.')
if propertyClass is Batman.Keypath or remainingSegments.length is 1
Batman.Keypath.forBaseAndKey(base, remainingPath)
else
new Batman.Keypath(base, remainingPath)
terminalProperty: -> @slice -1
valueFromAccessor: ->
if @depth is 1 then super else @terminalProperty()?.getValue()
setValue: (val) -> if @depth is 1 then super else @terminalProperty()?.setValue(val)
unsetValue: -> if @depth is 1 then super else @terminalProperty()?.unsetValue()
# Observable
# ----------
# Batman.Observable is a generic mixin that can be applied to any object to allow it to be bound to.
# It is applied by default to every instance of `Batman.Object` and subclasses.
Batman.Observable =
isObservable: true
hasProperty: (key) ->
@_batman?.properties?.hasKey?(key)
property: (key) ->
Batman.initializeObject @
propertyClass = @propertyClass or Batman.Keypath
properties = @_batman.properties ||= new Batman.SimpleHash
properties.get(key) or properties.set(key, new propertyClass(this, key))
get: (key) ->
@property(key).getValue()
set: (key, val) ->
@property(key).setValue(val)
unset: (key) ->
@property(key).unsetValue()
getOrSet: (key, valueFunction) ->
currentValue = @get(key)
unless currentValue
currentValue = valueFunction()
@set(key, currentValue)
currentValue
# `forget` removes an observer from an object. If the callback is passed in,
# its removed. If no callback but a key is passed in, all the observers on
# that key are removed. If no key is passed in, all observers are removed.
forget: (key, observer) ->
if key
@property(key).forget(observer)
else
@_batman.properties?.forEach (key, property) -> property.forget()
@
# `fire` tells any observers attached to a key to fire, manually.
# `prevent` stops of a given binding from firing. `prevent` calls can be repeated such that
# the same number of calls to allow are needed before observers can be fired.
# `allow` unblocks a property for firing observers. Every call to prevent
# must have a matching call to allow later if observers are to be fired.
# `observe` takes a key and a callback. Whenever the value for that key changes, your
# callback will be called in the context of the original object.
observe: (key, args...) ->
@property(key).observe(args...)
@
observeAndFire: (key, args...) ->
@property(key).observeAndFire(args...)
@
# Objects
# -------
# `Batman.initializeObject` is called by all the methods in Batman.Object to ensure that the
# object's `_batman` property is initialized and it's own. Classes extending Batman.Object inherit
# methods like `get`, `set`, and `observe` by default on the class and prototype levels, such that
# both instances and the class respond to them and can be bound to. However, CoffeeScript's static
# class inheritance copies over all class level properties indiscriminately, so a parent class'
# `_batman` object will get copied to its subclasses, transferring all the information stored there and
# allowing subclasses to mutate parent state. This method prevents this undesirable behaviour by tracking
# which object the `_batman_` object was initialized upon, and reinitializing if that has changed since
# initialization.
Batman.initializeObject = (object) ->
if object._batman?
object._batman.check(object)
else
object._batman = new _Batman(object)
# _Batman provides a convienient, parent class and prototype aware place to store hidden
# object state. Things like observers, accessors, and states belong in the `_batman` object
# attached to every Batman.Object subclass and subclass instance.
Batman._Batman = class _Batman
constructor: (@object, mixins...) ->
$mixin(@, mixins...) if mixins.length > 0
# Used by `Batman.initializeObject` to ensure that this `_batman` was created referencing
# the object it is pointing to.
check: (object) ->
if object != @object
object._batman = new _Batman(object)
return false
return true
# `get` is a prototype and class aware property access method. `get` will traverse the prototype chain, asking
# for the passed key at each step, and then attempting to merge the results into one object.
# It can only do this if at each level an `Array`, `Hash`, or `Set` is found, so try to use
# those if you need `_batman` inhertiance.
get: (key) ->
# Get all the keys from the ancestor chain
results = @getAll(key)
switch results.length
when 0
undefined
when 1
results[0]
else
# And then try to merge them if there is more than one. Use `concat` on arrays, and `merge` on
# sets and hashes.
if results[0].concat?
results = results.reduceRight (a, b) -> a.concat(b)
else if results[0].merge?
results = results.reduceRight (a, b) -> a.merge(b)
results
# `getFirst` is a prototype and class aware property access method. `getFirst` traverses the prototype chain,
# and returns the value of the first `_batman` object which defines the passed key. Useful for
# times when the merged value doesn't make sense or the value is a primitive.
getFirst: (key) ->
results = @getAll(key)
results[0]
# `getAll` is a prototype and class chain iterator. When passed a key or function, it applies it to each
# parent class or parent prototype, and returns the undefined values, closest ancestor first.
getAll: (keyOrGetter) ->
# Get a function which pulls out the key from the ancestor's `_batman` or use the passed function.
if typeof keyOrGetter is 'function'
getter = keyOrGetter
else
getter = (ancestor) -> ancestor._batman?[keyOrGetter]
# Apply it to all the ancestors, and then this `_batman`'s object.
results = @ancestors(getter)
if val = getter(@object)
results.unshift val
results
# `ancestors` traverses the prototype or class chain and returns the application of a function to each
# object in the chain. `ancestors` does this _only_ to the `@object`'s ancestors, and not the `@object`
# itsself.
ancestors: (getter = (x) -> x) ->
results = []
# Decide if the object is a class or not, and pull out the first ancestor
isClass = !!@object.prototype
parent = if isClass
@object.__super__?.constructor
else
if (proto = Object.getPrototypeOf(@object)) == @object
@object.constructor.__super__
else
proto
if parent?
parent._batman?.check(parent)
# Apply the function and store the result if it isn't undefined.
val = getter(parent)
results.push(val) if val?
# Use a recursive call to `_batman.ancestors` on the ancestor, which will take the next step up the chain.
if parent._batman?
results = results.concat(parent._batman.ancestors(getter))
results
set: (key, value) ->
@[key] = value
# `Batman.Object` is the base class for all other Batman objects. It is not abstract.
class BatmanObject extends Object
Batman.initializeObject(this)
Batman.initializeObject(@prototype)
# Setting `isGlobal` to true will cause the class name to be defined on the
# global object. For example, Batman.Model will be aliased to window.Model.
# This should be used sparingly; it's mostly useful for debugging.
@global: (isGlobal) ->
return if isGlobal is false
Batman.container[$functionName(@)] = @
# Apply mixins to this class.
@classMixin: -> $mixin @, arguments...
# Apply mixins to instances of this class.
@mixin: -> @classMixin.apply @prototype, arguments
mixin: @classMixin
counter = 0
_objectID: ->
@_objectID = -> c
c = counter++
hashKey: ->
return if typeof @isEqual is 'function'
@hashKey = -> key
key = "<Batman.Object #{@_objectID()}>"
toJSON: ->
obj = {}
for own key, value of @ when key not in ["_batman", "hashKey", "_objectID"]
obj[key] = if value.toJSON then value.toJSON() else value
obj
# Accessor implementation. Accessors are used to create properties on a class or prototype which can be fetched
# with get, but are computed instead of just stored. This is a batman and old browser friendly version of
# `defineProperty` without as much goodness.
#
# Accessors track which other properties they rely on for computation, and when those other properties change,
# an accessor will recalculate its value and notifiy its observers. This way, when a source value is changed,
# any dependent accessors will automatically update any bindings to them with a new value. Accessors accomplish
# this feat by tracking `get` calls, do be sure to use `get` to retrieve properties inside accessors.
#
# `@accessor` or `@classAccessor` can be called with zero, one, or many keys to attach the accessor to. This
# has the following effects:
#
# * zero: create a `defaultAccessor`, which will be called when no other properties or accessors on an object
# match a keypath. This is similar to `method_missing` in Ruby or `#doesNotUnderstand` in Smalltalk.
# * one: create a `keyAccessor` at the given key, which will only be called when that key is `get`ed.
# * many: create `keyAccessors` for each given key, which will then be called whenever each key is `get`ed.
#
# Note: This function gets called in all sorts of different contexts by various
# other pointers to it, but it acts the same way on `this` in all cases.
getAccessorObject = (accessor) ->
accessor = {get: accessor} if !accessor.get && !accessor.set && !accessor.unset
accessor
@classAccessor: (keys..., accessor) ->
Batman.initializeObject @
# Create a default accessor if no keys have been given.
if keys.length is 0
# The `accessor` argument is wrapped in `getAccessorObject` which allows functions to be passed in
# as a shortcut to {get: function}
@_batman.defaultAccessor = getAccessorObject(accessor)
else
# Otherwise, add key accessors for each key given.
@_batman.keyAccessors ||= new Batman.SimpleHash
@_batman.keyAccessors.set(key, getAccessorObject(accessor)) for key in keys
# Support adding accessors to the prototype from within class defintions or after the class has been created
# with `KlassExtendingBatmanObject.accessor(keys..., accessorObject)`
@accessor: -> @classAccessor.apply @prototype, arguments
# Support adding accessors to instances after creation
accessor: @classAccessor
constructor: (mixins...) ->
@_batman = new _Batman(@)
@mixin mixins...
# Make every subclass and their instances observable.
@classMixin Batman.EventEmitter, Batman.Observable
@mixin Batman.EventEmitter, Batman.Observable
# Observe this property on every instance of this class.
@observeAll: -> @::observe.apply @prototype, arguments
@singleton: (singletonMethodName="sharedInstance") ->
@classAccessor singletonMethodName,
get: -> @["_#{singletonMethodName}"] ||= new @
Batman.Object = BatmanObject
class Batman.Accessible extends Batman.Object
constructor: -> @accessor.apply(@, arguments)
class Batman.TerminalAccessible extends Batman.Accessible
propertyClass: Batman.Property
# Collections
Batman.Enumerable =
isEnumerable: true
map: (f, ctx = Batman.container) -> r = []; @forEach(-> r.push f.apply(ctx, arguments)); r
every: (f, ctx = Batman.container) -> r = true; @forEach(-> r = r && f.apply(ctx, arguments)); r
some: (f, ctx = Batman.container) -> r = false; @forEach(-> r = r || f.apply(ctx, arguments)); r
reduce: (f, r) ->
count = 0
self = @
@forEach -> if r? then r = f(r, arguments..., count, self) else r = arguments[0]
r
filter: (f) ->
r = new @constructor
if r.add
wrap = (r, e) -> r.add(e) if f(e); r
else if r.set
wrap = (r, k, v) -> r.set(k, v) if f(k, v); r
else
r = [] unless r.push
wrap = (r, e) -> r.push(e) if f(e); r
@reduce wrap, r
# Provide this simple mixin ability so that during bootstrapping we don't have to use `$mixin`. `$mixin`
# will correctly attempt to use `set` on the mixinee, which ends up requiring the definition of
# `SimpleSet` to be complete during its definition.
$extendsEnumerable = (onto) -> onto[k] = v for k,v of Batman.Enumerable
class Batman.SimpleHash
constructor: (obj) ->
@_storage = {}
@length = 0
@update(obj) if obj?