rivets.coffee
14.2 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
# rivets.js
# version : 0.4.5
# author : Michael Richards
# license : MIT
# The Rivets namespace.
Rivets = {}
# Polyfill For String::trim.
unless String::trim then String::trim = -> @replace /^\s+|\s+$/g, ''
findBinder = (type) ->
unless binder = Rivets.binders[type]
binder = Rivets.binders['*']
for identifier, value of Rivets.binders
if identifier isnt '*' and identifier.indexOf('*') isnt -1
regexp = new RegExp "^#{identifier.replace('*', '(.+)')}$"
if regexp.test type
binder = value
args = regexp.exec type
args.shift()
if binder instanceof Function
binder = {routine: binder}
[binder, args]
# A single binding between a model attribute and a DOM element.
class Rivets.Binding
# All information about the binding is passed into the constructor; the DOM
# element, the type of binding, the model object and the keypath at which
# to listen for changes.
constructor: (@el, @type, @model, @keypath, options) ->
@options = (options ||= {})
[@binder, @args] = if options.binder
[options.binder, options.args]
else
findBinder type
@formatters = options.formatters || []
# Applies all the current formatters to the supplied value and returns the
# formatted value.
formattedValue: (value) =>
model = @model
for formatter in @formatters
args = formatter.split /\s+/
id = args.shift()
m = Rivets.config.adapter.read model, id
formatter = if m instanceof Function
m
else
Rivets.formatters[id]
if formatter?.read instanceof Function
value = formatter.read value, args...
else if formatter instanceof Function
value = formatter value, args...
value
# Sets the value for the binding. This Basically just runs the binding routine
# with the suplied value formatted.
set: (value) =>
binder = @binder
value = @formattedValue if value instanceof Function and !binder.function
value.call @model, @options.bindContext
else
value
binder.routine?.call @, @el, value
# Syncs up the view binding with the model.
sync: =>
keypath = @keypath
model = @model
@set if @options.bypass
model[keypath]
else
Rivets.config.adapter.read model, keypath
# Publishes the value currently set on the input element back to the model.
publish: =>
value = getInputValue @el
for formatter in @formatters.slice(0).reverse()
args = formatter.split /\s+/
id = args.shift()
f = Rivets.formatters[id]
if f?.publish
value = f.publish value, args...
Rivets.config.adapter.publish @model, @keypath, value
# Subscribes to the model for changes at the specified keypath. Bi-directional
# routines will also listen for changes on the element to propagate them back
# to the model.
bind: =>
@binder.bind?.call @, @el
if @options.bypass
@sync()
else
Rivets.config.adapter.subscribe @model, @keypath, @sync if @keypath
@sync() if Rivets.config.preloadData
loopDeps @, (model, keypath) => Rivets.config.adapter.subscribe model, keypath, @sync
# Unsubscribes from the model and the element.
unbind: =>
@binder.unbind?.call @, @el
unless @options.bypass
Rivets.config.adapter.unsubscribe @model, @keypath, @sync if @keypath
loopDeps @, (model, keypath) => Rivets.config.adapter.unsubscribe model, keypath, @sync
loopDeps = (binder, callback) ->
if binder.options.dependencies?.length
for dependency in binder.options.dependencies
if /^\./.test dependency
model = binder.model
keypath = dependency.substr 1
else
dependency = dependency.split '.'
model = Rivets.config.adapter.read binder.view.models dependency.shift()
keypath = dependency.join '.'
callback model, keypath
expressionRegex = /(.*?)\{\{([^{}]+)\}\}/
createSubExpressionBinder = (outerBinding, values, i) ->
values[i] = null
routine: (el, value) ->
values[i] = value
outerBinding.sync()
defaultExpressionParser = (view, node, type, models, value) ->
if expressionRegex.test value
binding = new Rivets.Binding node, type, models
values = []
subs = []
while value && expressionRegex.test value
matches = expressionRegex.exec value
value = value.substring matches[0].length
values[values.length] = matches[1] if matches[1]
subs[subs.length] = subBinding = defaultExpressionParser view, null, '*', models, matches[2]
subBinding.binder = createSubExpressionBinder binding, values, values.length
values[values.length] = value if value
bindMethod = binding.bind
unbindMethod = binding.unbind
binding.sync = ->
binding.set values.join ''
# Publishes the value currently set on the input element back to the model.
binding.publish = ->
# can't really do anything with this
# Subscribes to the model for changes at the specified keypath. Bi-directional
# routines will also listen for changes on the element to propagate them back
# to the model.
binding.bind = ->
bindMethod()
for sub in subs
sub.bind()
# Unsubscribes from the model and the element.
binding.unbind = ->
unbindMethod()
for sub in subs
sub.unbind()
return binding
pipes = (pipe.trim() for pipe in value.split '|')
context = (ctx.trim() for ctx in pipes.shift().split '<')
path = context.shift()
splitPath = path.split /\.|:/
options =
formatters: pipes
bypass: path.indexOf(':') != -1
bindContext: models
parsingSupport = Rivets.config.adapter.parsingSupport
[options.binder, options.args] = findBinder type
firstPart = if parsingSupport
splitPath[0]
else
splitPath.shift()
model = if firstPart
Rivets.config.adapter.read models, firstPart
else
models
keypath = splitPath.join '.'
if model
if dependencies = context.shift()
options.dependencies = dependencies.split /\s+/
binding = new Rivets.Binding node, type, (if parsingSupport then models else model), keypath, options
binding.view = view
binding
# A collection of bindings built from a set of parent elements.
class Rivets.View
# The DOM elements and the model objects for binding are passed into the
# constructor.
constructor: (els, @models) ->
@els = if (els.jquery || els instanceof Array) then els else [els]
@build()
# Regular expression used to match binding attributes.
bindingRegExp: =>
prefix = Rivets.config.prefix
if prefix then new RegExp("^data-#{prefix}-") else /^data-/
# Parses the DOM tree and builds Rivets.Binding instances for every matched
# binding declaration. Subsequent calls to build will replace the previous
# Rivets.Binding instances with new ones, so be sure to unbind them first.
build: =>
bindings = @bindings = []
skipNodes = []
bindingRegExp = @bindingRegExp()
parse = (node) =>
unless node in skipNodes
for attribute in node.attributes
if bindingRegExp.test attribute.name
type = attribute.name.replace bindingRegExp, ''
unless binder = Rivets.binders[type]
for identifier, value of Rivets.binders
if identifier isnt '*' and identifier.indexOf('*') isnt -1
regexp = new RegExp "^#{identifier.replace('*', '.+')}$"
if regexp.test type
binder = value
binder or= Rivets.binders['*']
if binder.block
skipNodes.push n for n in node.getElementsByTagName '*'
attributes = [attribute]
for attribute in attributes or node.attributes
if bindingRegExp.test attribute.name
type = attribute.name.replace bindingRegExp, ''
binding = defaultExpressionParser @, node, type, @models, attribute.value
if binding
bindings.push binding
attributes = null if attributes
return
for el in @els
parse el
parse node for node in el.getElementsByTagName '*' when node.attributes?
return
# Returns an array of bindings where the supplied function evaluates to true.
select: (fn) =>
binding for binding in @bindings when fn binding
# Binds all of the current bindings for this view.
bind: =>
@bindings.map (binding) -> binding.bind()
# Unbinds all of the current bindings for this view.
unbind: =>
@bindings.map (binding) -> binding.unbind()
# Syncs up the view with the model by running the routines on all bindings.
sync: =>
@bindings.map (binding) -> binding.sync()
# Publishes the input values from the view back to the model (reverse sync).
publish: =>
(@select (b) -> b.binder.publishes).map (binding) -> binding.publish()
# Cross-browser event binding.
bindEvent = (el, event, handler, context, bindContext) ->
fn = (e) -> handler.call context, e, bindContext
# Check to see if jQuery is loaded.
if window.jQuery?
el = jQuery el
if el.on? then el.on event, fn else el.bind event, fn
# Check to see if addEventListener is available.
else if window.addEventListener?
el.addEventListener event, fn, false
else
# Assume we are in IE and use attachEvent.
event = 'on' + event
el.attachEvent event, fn
fn
# Cross-browser event unbinding.
unbindEvent = (el, event, fn) ->
# Check to see if jQuery is loaded.
if window.jQuery?
el = jQuery el
if el.off? then el.off event, fn else el.unbind event, fn
# Check to see if addEventListener is available.
else if window.removeEventListener
el.removeEventListener event, fn, false
else
# Assume we are in IE and use attachEvent.
event = 'on' + event
el.detachEvent event, fn
# Returns the current input value for the specified element.
getInputValue = (el) ->
switch el.type
when 'checkbox' then el.checked
when 'select-multiple' then o.value for o in el when o.selected
else el.value
iterate = (collection, callback) ->
if Rivets.config.adapter.iterate
Rivets.config.adapter.iterate collection, callback
else if collection instanceof Array
callback(item, i) for item, i in collection
else
callback(m, n) for n, m of collection
convertToModel = (data) ->
if Rivets.config.adapter.convertToModel
Rivets.config.adapter.convertToModel(data)
else
data
# Core binding routines.
createInputBinder = (routine) ->
publishes: true
bind: (el) ->
@currentListener = bindEvent el, 'change', @publish
unbind: (el) ->
unbindEvent el, 'change', @currentListener
routine: routine
Rivets.binders =
enabled: (el, value) ->
el.disabled = !value
disabled: (el, value) ->
el.disabled = !!value
checked: createInputBinder (el, value) ->
el.checked = if el.type is 'radio'
el.value is value
else
!!value
unchecked: createInputBinder (el, value) ->
el.checked = if el.type is 'radio'
el.value isnt value
else
!value
show: (el, value) ->
el.style.display = if value then '' else 'none'
hide: (el, value) ->
el.style.display = if value then 'none' else ''
html: (el, value) ->
el.innerHTML = if value? then value else ''
value: createInputBinder (el, value) ->
if el.type is 'select-multiple'
o.selected = o.value in value for o in el if value?
else
el.value = if value? then value else ''
text: (el, value) ->
newValue = if value? then value else ''
if el.innerText?
el.innerText = newValue
else
el.textContent = newValue
"on-*":
function: true
routine: (el, value) ->
firstArg = @args[0]
currentListener = @currentListener
unbindEvent el, firstArg, currentListener if currentListener
@currentListener = bindEvent el, firstArg, value, @model, @options.bindContext
"each-*":
block: true
bind: (el, collection) ->
el.removeAttribute ['data', rivets.config.prefix, @type].join('-').replace '--', '-'
routine: (el, collection) ->
iterated = @iterated
if iterated?
for view in iterated
view.unbind()
e.parentNode.removeChild e for e in view.els
else
marker = @marker = document.createComment " rivets: #{@type} "
parentNode = el.parentNode
parentNode.insertBefore marker, el
parentNode.removeChild el
@iterated = iterated = []
if collection
marker = @marker
iterate collection, (item, i) =>
data = {}
iterate @view.models, (item, i) => data[i] = item
data[@args[0]] = item
data["#{@args[0]}_index"] = data['rivets_index'] = i
data = convertToModel data
itemEl = el.cloneNode true
previous = if iterated.length > 0
iterated[iterated.length - 1].els[0]
else
marker
marker.parentNode.insertBefore itemEl, previous.nextSibling ? null
iterated.push rivets.bind itemEl, data
"class-*": (el, value) ->
elClass = " #{el.className} "
if !value is (elClass.indexOf(" #{@args[0]} ") isnt -1)
el.className = if value
"#{el.className} #{@args[0]}"
else
elClass.replace(" #{@args[0]} ", ' ').trim()
"*": (el, value) ->
if value
el.setAttribute @type, value
else
el.removeAttribute @type
# Default configuration.
Rivets.config =
preloadData: true
# Default formatters. There aren't any.
Rivets.formatters = {}
# The rivets module. This is the public interface that gets exported.
rivets =
# Exposes the core binding routines that can be extended or stripped down.
binders: Rivets.binders
# Exposes the formatters object to be extended.
formatters: Rivets.formatters
# Exposes the rivets configuration options. These can be set manually or from
# rivets.configure with an object literal.
config: Rivets.config
# Sets configuration options by merging an object literal.
configure: (options) ->
options ||= {}
for property, value of options
Rivets.config[property] = value
return
# Binds a set of model objects to a parent DOM element. Returns a Rivets.View
# instance.
bind: (el, models) ->
models ||= {}
view = new Rivets.View(el, models)
view.bind()
view
# Exports rivets for both CommonJS and the browser.
if module?
module.exports = rivets
else
@rivets = rivets