English 中文(简体)
主干js: 视图模块中的收藏初始化模块只有一个模型
原标题:backbonejs: the collection initialize in view module have only one model

我有一个model :

window.LayerModel = Backbone.Model.extend({

        defaults:{
             id : unknow ,
             type : unkonw ,
             preId : unknow ,

             data : {}
        }
}

然后我定义了一个集合:

window.LayerManageCollection = Backbone.Collection.extend({
            model: LayerModel
    }) 

然后我就把它写进去看:

        window.LayerMasterManageView = Backbone.View.extend({

              initialize: function () {
                  //here I have a gobal javascript variable named "localdata"
                  //which have 17 items in an array,each of them is object type

                  this.collection = new LayerManageCollection(localdata);
                  console.log( this collection , this.collection);
              }
}

但收藏的长度是1!只有一种型号。

奇怪的是,如果将 默认值 更改为 默认值 , 收藏结果会像我所希望的那样, 长度为 17 。

为什么发生这种事 我怎样才能解决这个问题?

最佳回答

默认 idAtritte 是一个模型。由于您在 defaults 中重新定义了 id 。由于您在 defaults 中定义了 < > /code>,您将永远创建同样的模型,因为创建重复的模型时, Backbone会悄悄地出错,所以您只看到一个模型。

问题回答

i think your problem is with the objects present in your localdata.
how many objects in your localdata have different id field
either you should provide different id to every object in your localdata array or just remove the id field from defaults in the model LayerModel

whenever you change the name from defaults to default then because there is no default id backbone takes it as a new model and hence adds it to the collection.

so you can change defaults to any other name like abc and it will have the same behaviour





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.