问题描述:

I don't know how to change array into collection.

here is what I want to do (coffeeScript)

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

@filters = new Backbone.Collection(myArray)

what I am getting is

Backbone.Collection {length: 9, models: Array[7]...}

but each model inside the collection looks weird:

attributes:

Object 0: "s"

1: "t"

2: "r"

3: "1"

how can i construct collection so as i have attribute { name : str1 }

网友答案:

I think Backbone Models expect an object not a string. Convert the array to a set of objects:

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

Allow me to give an explanation as to what is happening here,

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

this part takes in your array and stores it within myArray

myModels = for name in myArray then {name}

the above line of code creates a for loop that loops through the Array. It loops through the array a total number of times equal to myArray.length

@filters = new Backbone.Collection(myModels)

The above line of code creates a new backbone collection that is based off of the for loop, i.e it then loops through the for loop and stores the result in a collection.

相关阅读:
Top