【问题标题】:building backbone collection for array为数组构建主干集合
【发布时间】:2015-01-20 23:36:15
【问题描述】:

我不知道如何将数组更改为集合。 这是我想做的(coffeeScript)

myArray = ['str1', 'str2', 'str3', 'str4', 'str5', 'str6', 'str7']
@filters = new Backbone.Collection(myArray)

我得到的是 Backbone.Collection {length: 9, models: Array[7]...}

但集合中的每个模型看起来都很奇怪:

attributes:
     Object 0: "s"
            1: "t"
            2: "r"
            3: "1"

如何构造集合,以便我拥有属性 { name : str1 }

【问题讨论】:

    标签: arrays backbone.js coffeescript


    【解决方案1】:

    我认为主干模型需要一个对象而不是字符串。将数组转换为一组对象:

    myArray = ['str1', 'str2', 'str3', 'str4', 'str5', 'str6', 'str7']
    myModels = for name in myArray then {name}
    @filters = new Backbone.Collection(myModels)
    

    【讨论】:

    • 很有趣,但是您的代码正在生成具有一个模型名称的集合:str7 我怎样才能得到它们?
    【解决方案2】:

    请允许我解释一下这里发生了什么,

    myArray = ['str1', 'str2', 'str3', 'str4', 'str5', 'str6', 'str7']
    

    这部分接收您的数组并将其存储在 myArray 中

    myModels = for name in myArray then {name}
    

    上面的代码行创建了一个循环遍历数组的for循环。它遍历数组的总次数等于 myArray.length

    @filters = new Backbone.Collection(myModels)
    

    上面的代码行创建了一个基于 for 循环的新主干集合,即它然后循环通过 for 循环并将结果存储在一个集合中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多