如何触发fetch方法以及如何设置url

时间:2012-05-17 10:49:22

标签: backbone.js

我正在根据@ 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
});

1 个答案:

答案 0 :(得分:1)

您想要探索两条路径

使用您的模型数据预先填充您的收藏

在您的示例中,您已经在执行此操作,但是您要获取一个集合,集合网址为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上使用它。