覆盖Backbone的Collection-fetch

Dan*_*Woo 26 javascript backbone.js web

我想以非RESTful方式获取我的集合,所以我决定覆盖Collection.fetchwith

App.carClc = Backbone.Collection.extend({
    model : App.cardModel,
    url : 'http://localhost/bbtest/data.php',
    fetch : function() {
        $.ajax({
            type : 'GET',
            url : this.url,
            success : function(data) {
                console.log(data);
            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

我不知道如何将我的集合设置为响应.我是BackboneJS的新手,谢谢大家!

Pra*_*mod 58

如果要添加自定义"装饰器" fetch,但不完全覆盖它,请尝试:

    var MyCollection = Backbone.Collection.extend({

        //custom methods

        fetch: function(options) {

            //do specific pre-processing 

            //Call Backbone's fetch
            return Backbone.Collection.prototype.fetch.call(this, options);
        }

  });    
Run Code Online (Sandbox Code Playgroud)

在这里,您不必自己推出 $.ajax

另外,return如果你想使用Backbone fetch方法返回的jQuery保证,请不要忘记在最后一行.

有关详细信息,请参阅http://japhr.blogspot.in/2011/10/overriding-url-and-fetch-in-backbonejs.html.

  • 这个答案对我来说感觉更干净,并且允许你不限制自己的任何其他功能.fetch()有你可能想稍后使用. (5认同)
  • @JRM你能扩展一下吗? (2认同)

nxt*_*rld 30

Backbone集合有两种方法来设置新数据的添加和重置.假设您想要使用传入数据替换所有收集数据,因此使用重置:

 App.carClc = Backbone.Collection.extend({
model : App.cardModel,
url : 'http://localhost/bbtest/data.php',
fetch : function() {
    // store reference for this collection
    var collection = this;
    $.ajax({
        type : 'GET',
        url : this.url,
        dataType : 'json',
        success : function(data) {
            console.log(data);
            // set collection data (assuming you have retrieved a json object)
            collection.reset(data)
        }
    });
}
})
Run Code Online (Sandbox Code Playgroud)