forked from schneiderik/fields
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfields.coffee
More file actions
380 lines (290 loc) · 11.4 KB
/
fields.coffee
File metadata and controls
380 lines (290 loc) · 11.4 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
# fields
# An attempt at making data collection from server rendered fields easier.
# by Erik Schneider
########
# Events
# This even system is taken from Backbone.Events and converted to coffeescript.
# I needed a way to call and bind to events outside of jQuery and Backbone was the
# first thing I thought of to implement this.
# So, thank you to Jeremy Ashkenas and all of the Backbone contributors for this
# event framework.
# Regular expression used to split event strings
eventSplitter = /\s+/
# A module that can be mixed in to *any object* in order to provide it with
# custom events. You may bind with `on` or remove with `off` callback functions
# to an event; `trigger`-ing an event fires all callbacks in succession.
#
# var object = {};
# _.extend(object, Backbone.Events);
# object.on('expand', function(){ alert('expanded'); });
# object.trigger('expand');
class Events
# Bind one or more space separated events, `events`, to a `callback`
# function. Passing `"all"` will bind the callback to all events fired.
on: (events, callback, context)->
return @ unless callback
events = events.split(eventSplitter)
calls = this._callbacks or (this._callbacks = {})
for event in events
list = calls[event] or (calls[event] = [])
list.push callback, context
@
# Remove one or many callbacks. If `context` is null, removes all callbacks
# with that function. If `callback` is null, removes all callbacks for the
# event. If `events` is null, removes all bound callbacks for all events.
off: (events, callback, context)->
# No events, or removing *all* events.
return @ unless (calls = this._callbacks)
unless (events or callback or context)
delete this._callbacks
return @
events = if events
events.split(eventSplitter)
else
getKeys = Object.keys || (obj)->
if obj isnt Object(obj)
throw new TypeError('Invalid object')
keys = []
for key of obj
keys[keys.length] = key if hasOwnProperty.call(obj, key)
return keys
getKeys(calls)
# Loop through the callback list, splicing where appropriate.
while event = events.shift()
if !(list = calls[event]) or !(callback or context)
delete calls[event]
continue
i = list.length - 2
while i >= 0
list.splice i, 2 unless callback and list[i] isnt callback or context and list[i + 1] isnt context
i -= 2
return @
# Trigger one or many events, firing all bound callbacks. Callbacks are
# passed the same arguments as `trigger` is, apart from the event name
# (unless you're listening on `"all"`, which will cause your callback to
# receive the true name of the event as the first argument).
trigger: (events)->
return @ unless @_callbacks
calls = @_callbacks
rest = []
events = events.split(eventSplitter)
# Fill up `rest` with the callback arguments. Since we're only copying
# the tail of `arguments`, a loop is much faster than Array#slice.
i = 1
length = arguments.length
while i < length
rest[i - 1] = arguments[i]
i++
# For each event, walk through the list of callbacks twice, first to
# trigger the event, then to trigger any `"all"` callbacks.
for event in events
# Copy callback lists to prevent modification.
if all = calls.all
all = all.slice()
if list = calls[event]
list = list.slice()
# Execute event callbacks.
if list
i = 0
length = list.length
while i < length
list[i].apply (list[i + 1] or @), rest
i += 2
# Execute "all" callbacks.
if all
args = [event].concat(rest)
i = 0
length = all.length
while i < length
all[i].apply all[i + 1] or this, args
i += 2
return @
# Aliases for backwards compatibility.
Events.bind = Events.on
Events.unbind = Events.off
#############
# Field Model
class Field extends Events
constructor: (element, parent='body', requiredErrorMessage='Field required')->
@el = $(element)
@parent = $(parent)
@attributes = {}
@val = @value
@requiredErrorMessage = requiredErrorMessage
# Update attributes when a user interacts with the field
@parent.find("[name='#{@el.attr('name')}']").on 'keyup blur focus change', (e, options={})=>
return if options.silent
@value @getFieldValueFromDOM(), {silent: true}
# Evaluate the field for any errors, warnings, etc. when the value changes
@on 'change:value', (model, value)=>
@attributes.empty = @isEmpty()
@evaluate()
@setAttributes()
@
setAttributes: ->
@attributes.name = @el.attr 'name'
@attributes.type = @el.attr 'type'
@attributes.value = @getFieldValueFromDOM()
@attributes.required = @isRequired()
@attributes.empty = @isEmpty()
@attributes.evaluations = {}
@evaluate()
isEmpty: ()->
return true if @val() is undefined
return true if @val().length is 0
return true if @val() is []
return false
isRequired: ()->
return true if @el.hasClass 'required'
return true if @el.is('[required]')
return false
isValid: ()->
return false if @get('evaluations').errors?
return true
# Get value of an attribute at a specific key
get: (attr)->
return @attributes[attr]
# Get value of the field, or set it by passing an argument
value: (arg, options={})->
return @get('value') unless arg?
return @get('value') if @get('value') is arg
@attributes.value = arg
@trigger "change:value", @, arg
@updateFieldValueInDOM arg unless options.silent
return @
# Convenience method for setting the value back to nothing
clear: ->
@value ''
errors: ->
if @get('evaluations').errors?
return @get('evaluations').errors
else
return []
# Evaluate the field against evaluations stored in the evaluationRegistry and
# return an object of any results keyed on the context of the evaluation. i.e. 'errors'
evaluate: ->
@attributes.evaluations = {}
if @isRequired() and @el.is(':visible')
if @isEmpty()
@attributes.evaluations.errors = [@requiredErrorMessage]
else
$.extend @attributes.evaluations, window.FieldsUtils.evaluationRegistry.evaluate(@el)
# Trigger event if validity changes
@trigger('change:valid', @, @isValid()) unless @isValid() is @get('valid')
# A field is valid if it has no errors.
@attributes.valid = @isValid()
return @get('evaluations')
# Getting and setting values is a bit complicated because of radio and checkbox inputs.
# Only one field model should be generated for the set of inputs with the same name.
getFieldValueFromDOM: ()->
return @getRadioValueFromDOM() if @get('type') is 'radio'
return @getCheckboxValueFromDOM() if @get('type') is 'checkbox'
@el.val()
getRadioValueFromDOM: ()->
@parent.find("[name='#{@get('name')}']:checked").val()
getCheckboxValueFromDOM: ()->
vals = []
vals.push(@parent.find(input).val()) for input in @parent.find("[name='#{@get('name')}']:checked")
return vals
updateFieldValueInDOM: (value)->
return @updateRadioValueInDOM(value) if @get('type') is 'radio'
return @updateCheckboxValueInDOM(value) if @get('type') is 'checkbox'
@el.val(value)
updateRadioValueInDOM: (value)->
if @notInPossibleValues(value)
return @parent.find("[name='#{@get('name')}'][checked]").attr('checked', false).trigger('change', {silent: true})
@parent.find("[name='#{@get('name')}']").attr('checked', false)
@parent.find("[name='#{@get('name')}'][value='#{value}']").attr('checked', true).trigger('change', {silent: true})
updateCheckboxValueInDOM: (values)->
@parent.find("[name='#{@get('name')}']").attr('checked', false).trigger('change', {silent: true})
for value in values
break if @notInPossibleValues(value)
@parent.find("[name='#{@get('name')}'][value='#{value}']").attr('checked', true).trigger('change', {silent: true})
notInPossibleValues: (value)->
possible_values = ($(field).val() for field in @parent.find("[name='#{@get('name')}']"))
missing = true
missing = false for val in possible_values when val is value
return missing
#######################
# Evaluation Registry
class Evaluation
constructor: (selector, context, statement)->
@selector = selector
@context = context
@statement = statement
evaluate: (field)->
@statement(field)
class EvaluationRegistry extends Events
constructor: ()->
@evaluations = []
# Runs through all of the evaluations and calls any statements
# for evaluations that have a selector matching the provided field's selector.
evaluate: (field)->
results = {}
for evaluation in @evaluations when field.is evaluation.selector
result = evaluation.evaluate(field)
unless result is undefined
results[evaluation.context] = [] unless results[evaluation.context]?
results[evaluation.context].push result
return results
# Accepts one or an array of evaluation_attribute objects to create new
# Evaluations and add them to the registry.
add: (evaluations)->
# Convert evaluation to an array if you only passed one.
evaluations = [evaluations] if Object.prototype.toString.call(evaluations) is '[object Object]'
for e in evaluations
evaluation = new Evaluation(e.selector, e.context, e.statement)
@evaluations.push evaluation
return @
########
# Fields
class Fields extends Events
@within: (selector, requiredErrorMessage='Field required')->
return new Field(selector, requiredErrorMessage) if $(selector).is 'input:not([type="submit"]), select, textarea'
new Fields(selector, requiredErrorMessage)
@in = @at = @within
@all: (requiredErrorMessage='Field required')->
new Fields('body', requiredErrorMessage)
constructor: (selector='body', requiredErrorMessage='Field required')->
@fields = 'input:not([type="submit"]), select, textarea'
@el = $(selector)
@attributes = {}
@requiredErrorMessage = requiredErrorMessage
@generateModels()
@trackValidity()
for name, model of @models
model.on 'change:value', (e, value)=>
@trigger 'change:value', e.get('name'), value
return @
# Get a field model by it's name
get: (name)-> @models[name]
# Convenience method to clear the values of all of the fields in Fields
clear: ->
for name, model of @models
model.clear() unless model.el.is(':hidden')
return @
# Collect a specified value from each field model keyed on the name of that field.
collect: (value)->
dict = {}
for name, model of @models
dict[name] = model.get(value)
return dict
isValid: ()->
valid = true
valid = false for name, model of @models when model.isValid() is false
return valid
# Update the collections validity whenever one of its models validity changes
trackValidity: ()->
@attributes.valid = @isValid()
for name, model of @models
model.on 'change:valid', (e, value)=>
@trigger('change:valid', @, @isValid()) if @isValid() isnt @attributes.valid
@attributes.valid = @isValid()
generateModels: ()->
@models = {}
for field in @el.find @fields
unless @models[ $(field).attr('name') ]?
@models[$(field).attr('name')] = new Field(field, @el, @requiredErrorMessage)
window.FieldsUtils = {}
window.FieldsUtils.evaluationRegistry ||= new EvaluationRegistry
window.Fields ||= Fields