Repository navigation
Expand file tree
/
Copy pathspine.coffee
More file actions
652 lines (518 loc) · 15.5 KB
/
Copy pathspine.coffee
File metadata and controls
652 lines (518 loc) · 15.5 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
###
Spine.js MVC library
Released under the MIT License
###
Events =
bind: (ev, callback) ->
evs = ev.split(' ')
@_callbacks or= {} unless @hasOwnProperty('_callbacks')
for name in evs
@_callbacks[name] or= []
@_callbacks[name].push(callback)
this
one: (ev, callback) ->
@bind ev, handler = ->
@unbind(ev, handler)
callback.apply(this, arguments)
trigger: (args...) ->
ev = args.shift()
list = @_callbacks?[ev]
return unless list
for callback in list
break if callback.apply(this, args) is false
true
listenTo: (obj, ev, callback) ->
obj.bind(ev, callback)
@listeningTo or= []
@listeningTo.push {obj, ev, callback}
this
listenToOnce: (obj, ev, callback) ->
listeningToOnce = @listeningToOnce or= []
obj.bind ev, handler = ->
idx = -1
for lt, i in listeningToOnce when lt.obj is obj
idx = i if lt.ev is ev and lt.callback is handler
obj.unbind(ev, handler)
listeningToOnce.splice(idx, 1) unless idx is -1
callback.apply(this, arguments)
listeningToOnce.push {obj, ev, callback: handler}
this
stopListening: (obj, events, callback) ->
if arguments.length is 0
for listeningTo in [@listeningTo, @listeningToOnce]
continue unless listeningTo
for lt in listeningTo
lt.obj.unbind(lt.ev, lt.callback)
@listeningTo = undefined
@listeningToOnce = undefined
else if obj
for listeningTo in [@listeningTo, @listeningToOnce]
continue unless listeningTo
events = if events then events.split(' ') else [undefined]
for ev in events
for idx in [listeningTo.length-1..0]
lt = listeningTo[idx]
continue unless lt.obj is obj
continue if callback and lt.callback isnt callback
if (not ev) or (ev is lt.ev)
lt.obj.unbind(lt.ev, lt.callback)
listeningTo.splice(idx, 1) unless idx is -1
else if ev
evts = lt.ev.split(' ')
if ev in evts
evts = (e for e in evts when e isnt ev)
lt.ev = $.trim(evts.join(' '))
lt.obj.unbind(ev, lt.callback)
this
unbind: (ev, callback) ->
if arguments.length is 0
@_callbacks = {}
return this
return this unless ev
evs = ev.split(' ')
for name in evs
list = @_callbacks?[name]
continue unless list
unless callback
delete @_callbacks[name]
continue
for cb, i in list when (cb is callback)
list = list.slice()
list.splice(i, 1)
@_callbacks[name] = list
break
this
Events.on = Events.bind
Events.off = Events.unbind
Log =
trace: true
logPrefix: '(App)'
log: (args...) ->
return unless @trace
if @logPrefix then args.unshift(@logPrefix)
console?.log?(args...)
this
moduleKeywords = ['included', 'extended']
class Module
@include: (obj) ->
throw new Error('include(obj) requires obj') unless obj
for key, value of obj when key not in moduleKeywords
@::[key] = value
obj.included?.apply(this)
this
@extend: (obj) ->
throw new Error('extend(obj) requires obj') unless obj
for key, value of obj when key not in moduleKeywords
@[key] = value
obj.extended?.apply(this)
this
@proxy: (func) ->
=> func.apply(this, arguments)
proxy: (func) ->
=> func.apply(this, arguments)
constructor: ->
@init?(arguments...)
class Model extends Module
@extend Events
@include Events
@records : []
@irecords : {}
@attributes : []
@configure: (name, attributes...) ->
@className = name
@deleteAll()
@attributes = attributes if attributes.length
@attributes and= makeArray(@attributes)
@attributes or= []
@unbind()
this
@toString: -> "#{@className}(#{@attributes.join(", ")})"
@find: (id, notFound = @notFound) ->
@irecords[id]?.clone() or notFound?(id)
@findAll: (ids, notFound) ->
(@find(id) for id in ids when @find(id, notFound))
@notFound: (id) -> null
@exists: (id) -> Boolean @irecords[id]
@addRecord: (record,idx) ->
if root = @irecords[record.id or record.cid]
root.refresh(record)
else
record.id or= record.cid
@irecords[record.id] = @irecords[record.cid] = record
if idx isnt undefined
@records.splice(idx,0,record)
else
@records.push(record)
record
@refresh: (values, options = {}) ->
@deleteAll() if options.clear
records = @fromJSON(values)
records = [records] unless Array.isArray(records)
@addRecord(record) for record in records
@sort()
result = @cloneArray(records)
@trigger('refresh', result, options)
result
@select: (callback) ->
(record.clone() for record in @records when callback(record))
@findByAttribute: (name, value) ->
for record in @records
if record[name] is value
return record.clone()
null
@findAllByAttribute: (name, value) ->
@select (item) ->
item[name] is value
@each: (callback) ->
callback(record.clone()) for record in @records
@all: ->
@cloneArray(@records)
@slice: (begin = 0, end)->
@cloneArray(@records.slice(begin, end))
@first: (end = 1)->
if end > 1
@cloneArray(@records.slice(0, end))
else
@records[0]?.clone()
@last: (begin)->
if typeof begin is 'number'
@cloneArray(@records.slice(-begin))
else
@records[@records.length - 1]?.clone()
@count: ->
@records.length
@deleteAll: ->
@records = []
@irecords = {}
@destroyAll: (options) ->
record.destroy(options) for record in @records
@update: (id, atts, options) ->
@find(id).updateAttributes(atts, options)
@create: (atts, options) ->
record = new @(atts)
record.save(options)
@destroy: (id, options) ->
@find(id).destroy(options)
@change: (callbackOrParams) ->
if typeof callbackOrParams is 'function'
@bind('change', callbackOrParams)
else
@trigger('change', arguments...)
@fetch: (callbackOrParams) ->
if typeof callbackOrParams is 'function'
@bind('fetch', callbackOrParams)
else
@trigger('fetch', arguments...)
@toJSON: ->
@records
@beforeFromJSON: (objects) -> objects
@fromJSON: (objects) ->
return unless objects
if typeof objects is 'string'
objects = JSON.parse(objects)
objects = @beforeFromJSON(objects)
if Array.isArray(objects)
for value in objects
if value instanceof this
value
else
new @(value)
else
return objects if objects instanceof this
new @(objects)
@fromForm: ->
(new this).fromForm(arguments...)
@sort: ->
if @comparator
@records.sort @comparator
this
# Private
@cloneArray: (array) ->
(value.clone() for value in array)
@idCounter: 0
@uid: (prefix = '') ->
uid = prefix + @idCounter++
uid = @uid(prefix) if @exists(uid)
uid
# Instance
constructor: (atts) ->
super
if @constructor.uuid? and typeof @constructor.uuid is 'function'
@cid = @constructor.uuid()
@id = @cid unless @id
else
@cid = atts?.cid or @constructor.uid('c-')
@load atts if atts
isNew: ->
not @exists()
isValid: ->
not @validate()
validate: ->
load: (atts) ->
if atts.id then @id = atts.id
for key, value of atts
if typeof @[key] is 'function'
continue if typeof value is 'function'
@[key](value)
else
@[key] = value
this
attributes: ->
result = {}
for key in @constructor.attributes when key of this
if typeof @[key] is 'function'
result[key] = @[key]()
else
result[key] = @[key]
result.id = @id if @id
result
eql: (rec) ->
rec and rec.constructor is @constructor and
((rec.cid is @cid) or (rec.id and rec.id is @id))
save: (options = {}) ->
unless options.validate is false
error = @validate()
if error
@trigger('error', this, error)
return false
@trigger('beforeSave', this, options)
record = if @isNew() then @create(options) else @update(options)
@stripCloneAttrs()
@trigger('save', record, options)
record
stripCloneAttrs: ->
return if @hasOwnProperty 'cid' # Make sure it's not the raw object
for own key, value of this
delete @[key] if key in @constructor.attributes
this
updateAttribute: (name, value, options) ->
atts = {}
atts[name] = value
@updateAttributes(atts, options)
updateAttributes: (atts, options) ->
@load(atts)
@save(options)
changeID: (id) ->
return if id is @id
records = @constructor.irecords
records[id] = records[@id]
delete records[@id] unless @cid is @id
@id = id
@save()
remove: (options = {}) ->
# Remove record from model
records = @constructor.records.slice(0)
for record, i in records when @eql(record)
records.splice(i, 1)
break
@constructor.records = records
if options.clear
# Remove the ID and CID indexes
delete @constructor.irecords[@id]
delete @constructor.irecords[@cid]
destroy: (options = {}) ->
options.clear ?= true
@trigger('beforeDestroy', this, options)
@remove(options)
@destroyed = true
# handle events
@trigger('destroy', this, options)
@trigger('change', this, 'destroy', options)
@stopListening() if @listeningTo
@unbind()
this
dup: (newRecord = true) ->
atts = @attributes()
if newRecord
delete atts.id
else
atts.cid = @cid
record = new @constructor(atts)
@_callbacks and record._callbacks = @_callbacks unless newRecord
record
clone: ->
createObject(this)
reload: ->
return this if @isNew()
original = @constructor.find(@id)
@load(original.attributes())
original
refresh: (atts) ->
atts = @constructor.fromJSON(atts)
# ID change, need to do some shifting
if atts.id and @id isnt atts.id
@changeID(atts.id)
# go to the source and load attributes
@constructor.irecords[@id].load(atts)
@trigger('refresh', this)
@trigger('change', this, 'refresh')
this
toJSON: ->
@attributes()
toString: ->
"<#{@constructor.className} (#{JSON.stringify(this)})>"
fromForm: (form) ->
result = {}
for checkbox in $(form).find('[type=checkbox]:not([value])')
result[checkbox.name] = $(checkbox).prop('checked')
for checkbox in $(form).find('[type=checkbox][name$="[]"]')
name = checkbox.name.replace(/\[\]$/, '')
result[name] or= []
result[name].push checkbox.value if $(checkbox).prop('checked')
for key in $(form).serializeArray()
result[key.name] or= key.value
@load(result)
exists: ->
@constructor.exists(@id)
# Private
update: (options) ->
@trigger('beforeUpdate', this, options)
records = @constructor.irecords
records[@id].load @attributes()
@constructor.sort()
clone = records[@id].clone()
clone.trigger('update', clone, options)
clone.trigger('change', clone, 'update', options)
clone
create: (options) ->
@trigger('beforeCreate', this, options)
@id or= @cid
record = @dup(false)
@constructor.addRecord(record,options.idx)
@constructor.sort()
clone = record.clone()
clone.trigger('create', clone, options)
clone.trigger('change', clone, 'create', options)
clone
bind: ->
record = @constructor.irecords[@id] or this
Events.bind.apply record, arguments
one: ->
record = @constructor.irecords[@id] or this
Events.one.apply record, arguments
unbind: ->
record = @constructor.irecords[@id] or this
Events.unbind.apply record, arguments
trigger: ->
Events.trigger.apply this, arguments # fire off the instance event
return true if arguments[0] is 'refresh' # Don't trigger refresh events, because ... ?
@constructor.trigger arguments... # fire off the class event
Model::on = Model::bind
Model::off = Model::unbind
class Controller extends Module
@include Events
@include Log
eventSplitter: /^(\S+)\s*(.*)$/
tag: 'div'
constructor: (options) ->
@options = options
for key, value of @options
@[key] = value
@el = document.createElement(@tag) unless @el
@el = $(@el)
@el.addClass(@className) if @className
@el.attr(@attributes) if @attributes
@events = @constructor.events unless @events
@elements = @constructor.elements unless @elements
context = @
while parent_prototype = context.constructor.__super__
@events = $.extend({}, parent_prototype.events, @events) if parent_prototype.events
@elements = $.extend({}, parent_prototype.elements, @elements) if parent_prototype.elements
context = parent_prototype
@delegateEvents(@events) if @events
@refreshElements() if @elements
super
release: =>
@trigger 'release', this
# no need to unDelegateEvents since remove will end up handling that
@el.remove()
@unbind()
@stopListening()
$: (selector) -> @el.find(selector)
delegateEvents: (events) ->
for key, method of events
if typeof(method) is 'function'
# Always return true from event handlers
method = do (method) => =>
method.apply(this, arguments)
true
else
unless @[method]
throw new Error("#{method} doesn't exist")
method = do (method) => =>
@[method].apply(this, arguments)
true
match = key.match(@eventSplitter)
eventName = match[1]
selector = match[2]
if selector is ''
@el.bind(eventName, method)
else
@el.on(eventName, selector, method)
refreshElements: ->
for key, value of @elements
@[value] = @$(key)
delay: (func, timeout) ->
setTimeout(@proxy(func), timeout || 0)
# keep controllers elements obj in sync with it contents
html: (element) ->
@el.html(element.el or element)
@refreshElements()
@el
append: (elements...) ->
elements = (e.el or e for e in elements)
@el.append(elements...)
@refreshElements()
@el
appendTo: (element) ->
@el.appendTo(element.el or element)
@refreshElements()
@el
prepend: (elements...) ->
elements = (e.el or e for e in elements)
@el.prepend(elements...)
@refreshElements()
@el
replace: (element) ->
element = element.el or element
element = $.trim(element) if typeof element is "string"
# parseHTML is incompatible with Zepto
[previous, @el] = [@el, $($.parseHTML(element)?[0] or element)]
previous.replaceWith(@el)
@delegateEvents(@events)
@refreshElements()
@el
# Utilities & Shims
$ = window?.jQuery or window?.Zepto or (element) -> element
createObject = Object.create or (o) ->
Func = ->
Func.prototype = o
new Func()
makeArray = (args) ->
Array::slice.call(args, 0)
# Globals
Spine = @Spine = {}
module?.exports = Spine
Spine.version = '1.5.0'
Spine.$ = $
Spine.Events = Events
Spine.Log = Log
Spine.Module = Module
Spine.Controller = Controller
Spine.Model = Model
# Global events
Module.extend.call(Spine, Events)
# JavaScript compatability
Module.create = Module.sub =
Controller.create = Controller.sub =
Model.sub = (instances, statics) ->
class Result extends this
Result.include(instances) if instances
Result.extend(statics) if statics
Result.unbind?()
Result
Model.setup = (name, attributes = []) ->
class Instance extends this
Instance.configure(name, attributes...)
Instance
Spine.Class = Module