2

所以,我对 Backbone 还是很陌生。我的问题是:我有一个这样的集合:

...
isCollection: true,
parse: function(response) {
    if (response.status == 'ok') {
        this.page = response.result.page;
        this.count = response.result.count;
        this.total = response.result.total;
        this.sort = response.result.sort;
        this.ascending = response.result.ascending;
        this.myReports = response.result.results;
        return this;
    } else {

    }

this.myReports 是一个对象数组。我的问题是如何遍历数组(myReports)?我必须将其转换为集合吗?如果我尝试使用 .each,我会收到关于 .each 不受支持的错误。

谢谢你的帮助!

4

3 回答 3

0

您是否尝试像简单的 js 数组一样迭代它?

就像是:

for(var i in myArray){
   var item = myArray[i];
   //dosomething
}

也许值得尝试使用 underscorejs 来获得高级数组功能。

于 2013-10-24T15:07:43.140 回答
0

I would put the elements of response.result.results into the collection this way:

parse: function(response) {
    if (response.status == 'ok') {
        this.page = response.result.page;
        this.count = response.result.count;
        this.total = response.result.total;
        this.sort = response.result.sort;
        this.ascending = response.result.ascending;
        return response.result.results;
    } else {

    }
}

Now if fetching the collection succeeds, and response.status is 'ok', then:

  • your collection will have fields called page, count, total, sort and ascending,
  • these fields will contain the values you get as the fields of response.result,
  • the length of the collection will be the length of response.result.results, and
  • the items of the collection will be the items of response.result.results, so you can iterate over them inside the success handler of fetch.

If the fetch fails, or response.status is not 'ok', then the length of the collection will be zero. The fields page, count, total, sort and ascending will be undefined, unless you define them somewhere, for example in initialize or in the else branch inside the above parse function.

Here is a working example. The output is printed in the console, so e.g. in Chrome, press F12 and change to the Console tab. Anyway, since Backbone collections have a method called sort, I would change the name of the sort field to something else (sorted, toBeSorted, etc. - I don't know the semantics of this field).

于 2013-10-24T15:49:26.883 回答
0

当您调用myCollection.eachBackbone 集合时,您实际上是在调用 Underscore 的each方法,但它作为一种Backbone.Collection方法呈现给您会更好一些。

您可以只使用数组上的方法:

_.each(this.myReports, function (report) {
  // do whatever with report
})

是否应该将其转换为骨干集合是另一个问题。如果您想在其中存储模型,或使用任何Backbone.Collection功能,那么请务必使用上述每个方法对其进行转换。

于 2013-10-24T16:10:27.653 回答