1

我正在根据@20100 对这个问题的回答重新设计我的主干应用程序The best way to fetch and render a collection for a given object_id

请阅读对代码的评论,因为我认为更清楚,而且我的问题在较小的尺寸下看起来更好。


// My View
define([
    "js/collections/myCollection",
    "js/models/myFeed"
], function (MyCollection, MyModel) {
    var MyView = Backbone.View.extend({

        tagName: 'ul',

        initialize: function () {
            this.collection = new MyCollection();
            this.collection.on('add', this.onAddOne, this);
            this.collection.on('reset', this.onAddAll, this);

            // when I make myView = new MyView(_.extend( {el:this.$("#myView")} , this.options));
            // myView.render is not called
            // in order to trigger the render function I make the following… but probably there is a better way … 
            var that = this;
            this.collection.fetch({
                success: function () {
                    that.render();
                }
            });

        }
    });

    return MyView;
});

// MyCollection
define([
    "js/models/myModel"
], function (MyModel) {

    var MyCollection = Backbone.MyCollection.extend({
        model: MyModel, // add this
        url: function () {
            var url = "http://localhost/movies";

            return url; 
           // if I look to the GET request the url is without idAttribute
           // how can I attach the idAttribute to this url?
           // should bb takes care of this?

        }
    });

    return MyCollection;
});

//MyModel
define([
], function () {

    var MyModel = Backbone.MyModel.extend({
        idAttribute: 'object_id'
    });

    return MyModel
});
4

1 回答 1

1

有两条路你想探索

使用您的模型数据预填充您的集合

在您的示例中,您已经在执行此操作,但是您正在获取一个集合,集合 URL 是http://localhost/movies,如果您想要一个单独的模型,请查看下一点

仅在需要时获取每个单独的模型

假设您尝试在未预填充的集合上获取 ID 并且一次加载 1 个模型,您将不得不通过向您的集合添加一个方法来以自定义方式解决这个问题与此类似

getOrFetch: function(id, options) 
{
    var model;
    if (this.get(id)) 
    {
        model = this.get(id);
    } 
    else 
    {
      model = new this.model({
        id: id
      });
      this.add(model);
      model.fetch(options);
    }
    return model;
}

或添加该功能,Backbone.Collection.prototype.getOrFetch以便您可以在需要时在每个 Backbone Collection 上使用它。

于 2012-05-17T11:16:36.287 回答