-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathjquery.nested_attributes.coffee
316 lines (244 loc) · 9.69 KB
/
jquery.nested_attributes.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
###
Authors: Nick Giancola (@patbenatar), Brendan Loudermilk (@bloudermilk)
Homepage: https://github.com/patbenatar/jquery-nested_attributes
###
$ = jQuery
# jQuery selector for text-like inputs such as text or email
# Based on Mark Dalgleish and Thalimenel's sample code at http://markdalgleish.com/2011/05/jquery-selector-for-html5-input-types/
textInputTypes =
text: true
search: true
number: true
email: true
datetime: true
'datetime-local': true
date: true
month: true
week: true
time: true
tel: true
url: true
color: true
range: true
$.expr[':'].textall = (elem) ->
!!textInputTypes[elem.getAttribute('type')]
methods =
init: (options) ->
$el = $(@)
throw "Can't initialize more than one item at a time" if $el.length > 1
if $el.data("nestedAttributes")
throw "Can't initialize on this element more than once"
instance = new NestedAttributes($el, options)
$el.data("nestedAttributes", instance)
return $el
add: ->
$el = $(@)
unless $el.data("nestedAttributes")?
throw "You are trying to call instance methods without initializing first"
$el.data("nestedAttributes").addItem()
return $el
$.fn.nestedAttributes = (method) ->
if methods[method]?
return methods[method].apply @, Array.prototype.slice.call(arguments, 1)
else if typeof method == 'object' || !method
return methods.init.apply(@, arguments)
else
$.error("Method #{method} does not exist on jQuery.nestedAttributes")
class NestedAttributes
RELEVANT_INPUTS_SELECTOR: ":input[name][name!=\"\"]"
settings:
collectionName: false # If not provided, we will autodetect
bindAddTo: false # Required
removeOnLoadIf: false
collectIdAttributes: true
beforeAdd: false
afterAdd: false
beforeMove: false
afterMove: false
beforeDestroy: false
afterDestroy: false
destroySelector: '.destroy'
deepClone: true
$clone: null
######################
## ##
## Initialization ##
## ##
######################
constructor: ($el, options) ->
# This plugin gets called on the container
@$container = $el
# Merge default options
@options = $.extend({}, @settings, options)
# If the user provided a jQuery object to bind the "Add"
# bind it now or forever hold your peace.
@options.bindAddTo.click(@addClick) if @options.bindAddTo
# Cache all the items
@$items = @$container.children()
# If the user didn't provide a collectionName, autodetect it
unless @options.collectionName
@autodetectCollectionName()
# Initialize existing items
@$items.each (i, el) =>
$item = $(el)
# If the user wants us to attempt to collect Rail's ID attributes, do it now
# Using the default rails helpers, ID attributes will wind up right after their
# propper containers in the form.
if @options.collectIdAttributes and $item.is('input')
# Move the _id field into its proper container
$item.appendTo($item.prev())
# Remove it from the $items collection
@$items = @$items.not($item)
else
# Try to find and bind the destroy link if the user wanted one
@bindDestroy($item)
# Now that we've collected ID attributes
@hideIfAlreadyDestroyed $(item) for item in @$items
# Remove any items on load if the client implements a check and the check passes
if @options.removeOnLoadIf
@$items.each (i, el) =>
$el = $(el)
if $el.call(true, @options.removeOnLoadIf, i)
$el.remove()
########################
## ##
## Instance Methods ##
## ##
########################
autodetectCollectionName: ->
pattern = /\[(.[^\]]*)_attributes\]/
try
match = pattern.exec(@$items.first().find("#{@RELEVANT_INPUTS_SELECTOR}:first").attr('name'))[1]
if match != null
@options.collectionName = match
else
throw "Regex error"
catch error
console.log "Error detecting collection name", error
addClick: (event) =>
@addItem()
# Don't let the link do anything
event.preventDefault()
addItem: ->
# Piece together an item
newIndex = @$items.length
$newClone = @applyIndexToItem(@extractClone(), newIndex)
# Give the user a chance to make their own changes before we insert
if (@options.beforeAdd)
# Stop the add process if the callback returns false
return false if [email protected](undefined, $newClone, newIndex)
# Insert the new item after the last item
@$container.append($newClone)
# Give the user a chance to make their own changes after insertion
@options.afterAdd.call(undefined, $newClone, newIndex) if (@options.afterAdd)
# Add this item to the items list
@refreshItems()
extractClone: ->
# Are we restoring from an already created clone?
if @$restorableClone
$record = @$restorableClone
@$restorableClone = null
else
$record = @options.$clone || @$items.first()
# Make a deep clone (bound events and data)
$record = $record.clone(@options.deepClone)
@bindDestroy($record) if @options.$clone or [email protected]
# Empty out the values of text inputs and selects
$record.find('input:textall, input[type=file], textarea, select').val('')
# Reset checkboxes and radios
$record.find(':checkbox, :radio').attr("checked", false)
# Empty out any hidden [id] or [_destroy] fields
$record.find('input[name$="\\[id\\]"]').remove()
$record.find('input[name$="\\[_destroy\\]"]').remove()
# Make sure it's not hidden as we return.
# It would be hidden in the case where we're duplicating an
# already removed item for its template.
return $record.show()
applyIndexToItem: ($item, index) ->
collectionName = @options.collectionName
$item.find(@RELEVANT_INPUTS_SELECTOR).each (i, el) =>
$el = $(el)
idRegExp = new RegExp("_#{collectionName}_attributes_\\d+_")
idReplacement = "_#{collectionName}_attributes_#{index}_"
nameRegExp = new RegExp("\\[#{collectionName}_attributes\\]\\[\\d+\\]")
nameReplacement = "[#{collectionName}_attributes][#{index}]"
newID = $el.attr('id').replace(idRegExp, idReplacement) if $el.attr('id')
newName = $el.attr('name').replace(nameRegExp, nameReplacement)
$el.attr
id: newID
name: newName
$item.find('label[for]').each (i, el) =>
$el = $(el)
try
forRegExp = new RegExp("_#{collectionName}_attributes_\\d+_")
forReplacement = "_#{collectionName}_attributes_#{index}_"
newFor = $el.attr('for').replace(forRegExp, forReplacement)
$el.attr('for', newFor)
catch error
console.log "Error updating label", error
return $item
hideIfAlreadyDestroyed: ($item) ->
$destroyField = $item.find("[name$='[_destroy]']")
if $destroyField.length && $destroyField.val() == "true"
@destroy $item
# Hides a item from the user and marks it for deletion in the
# DOM by setting _destroy to true if the record already exists. If it
# is a new escalation, we simple delete the item
destroyClick: (event) =>
event.preventDefault()
@destroy $(event.target).parentsUntil(@$container).last()
destroy: ($item) ->
# If you're about to delete the last one,
# cache a clone of it first so we have something to show
# the next time user hits add
@$restorableClone = @extractClone() unless @$items.length-1
index = @indexForItem($item)
itemIsNew = $item.find('input[name$="\\[id\\]"]').length == 0
if (@options.beforeDestroy)
# Stop the destroy process if the callback returns false
return false if [email protected](undefined, $item, index, itemIsNew)
# Add a blank item row if none are visible after this deletion
@addItem() unless @$items.filter(':visible').length-1
if itemIsNew
$item.remove()
else
# Hide the item
$item.hide()
# Add the _destroy field
otherFieldName = $item.find(':input[name]:first').attr('name')
attributePosition = otherFieldName.lastIndexOf('[')
destroyFieldName = "#{otherFieldName.substring(0, attributePosition)}[_destroy]"
# First look for an existing _destroy field
$destroyField = $item.find("input[name='#{destroyFieldName}']")
# If it doesn't exist, create it
if $destroyField.length == 0
$destroyField = $("<input type=\"hidden\" name=\"#{destroyFieldName}\" />")
$item.append($destroyField)
$destroyField.val(true).change()
@options.afterDestroy.call($item, index, itemIsNew) if (@options.afterDestroy)
# Remove this item from the items list
@refreshItems()
# Rename the remaining items
@resetIndexes()
indexForItem: ($item) ->
regExp = new RegExp("\\[#{@options.collectionName}_attributes\\]\\[\\d+\\]")
name = $item.find("#{@RELEVANT_INPUTS_SELECTOR}:first").attr('name')
return parseInt(name.match(regExp)[0].split('][')[1].slice(0, -1), 10)
refreshItems: ->
@$items = @$container.children()
# Sets the proper association indices and labels to all items
# Used when removing items
resetIndexes: ->
@$items.each (i, el) =>
$el = $(el)
# Make sure this is actually a new position
oldIndex = @indexForItem($el)
return true if (i == oldIndex)
@options.beforeMove.call($el, i, oldIndex) if (@options.beforeMove)
# Change the number to the new index
@applyIndexToItem($el, i)
@options.afterMove.call($el, i, oldIndex) if (@options.afterMove)
bindDestroy: ($item) ->
$item.find(@options.destroySelector).click(@destroyClick) if (@options.destroySelector)
itemCount: ->
@$items.filter(':visible').length