Backbone - 使用用户输入的选项动态应用select2

时间:2014-04-18 01:47:42

标签: javascript backbone.js coffeescript jquery-select2

我正在用CoffeeScript编写一个Backbone应用程序。我也使用Select2进行下拉菜单。某些下拉菜单支持用户输入新的下拉选项。我可以这样做。但...

我的问题是我想通过在Backbone视图中循环遍历模型字段来动态地为用户创建的选项应用select2。

也许代码可以解释我做得更好。 (我希望)

# this is taken from the render method of my view
#
# Apply select2 widget for fields accepting user-created options
field_options = null
for field in @model.fields
    if field.fieldType == 'hidden' and field.show and field.options?
        field_options = field.options
        @$('input[name=' + field.name + ']').select2
            width: 'resolve'
            data: field_options
            createSearchChoice: (term) ->
                id: String(field_options.length + 1)
                text: term

如果只有一个字段接受用户创建的选项,则此代码有效。如果有两个字段,则field_options.length的长度始终相同(只有一个字段)。

我知道我有一个范围问题,但不明白如何纠正它。

请帮忙!我被困了

1 个答案:

答案 0 :(得分:1)

你的范围问题是你的select2函数持有field_options变量的引用,在循环中使用field_options但是当循环结束时,select2函数仍然保存对它的引用,这实际上意味着它获得了field_options收到的最后一个赋值的值。它很复杂,因为这是一个javascript错误。

你能做到的最好的事情就是把它转换成一个函数,与{}不同,函数有自己的范围。

我认为更简洁的做法是:

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?

这样函数捕获字段变量(因为函数具有它自己的作用域),并且在下一个循环中不会改变它