The problem with your scoping is that your select2 function is holding a reference to field_options
variable, field_options
is used inside the loop but when the loops end the select2 function still holds a reference to it, which actually mean it gets the value of the last assignment that field_options received. it is complicated, because this a javascript mistake.
The best thing you can do it just transform this to a function, functions, unlike {}
, has their own scope.
I think that a much more cleaner approach is this:
setSelect2 = (field) ->
@$('input[name=' + field.name + ']').select2
width: 'resolve'
data: field.options
createSearchChoice: (term) ->
id: String(field.options.length + 1)
text: term
setSelect2 field for field in @model.fields when field.fieldType == 'hidden' and field.show and field.options?
This way the function capture the field variable (because function has it's own scope) and it will not be changed in the next loop