26

我想以非 RESTful 方式获取我的收藏,所以我决定Collection.fetch

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);
            }
        });
    }
});

我不知道如何将我的收藏设置为响应。我是 BackboneJS 的新手,谢谢大家!

4

5 回答 5

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);
        }

  });    

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

return此外,如果您想使用 Backbone 方法返回的 jQuery 承诺,请不要忘记最后一行中的fetch

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

于 2013-01-13T07:11:19.127 回答
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)
        }
    });
}
})
于 2012-11-13T09:53:31.910 回答
3

我正在使用这样的东西:

$.when( $.ajax( URL, { dataType: "json" } ) )
    .then( $.proxy( function( response ) {
            ctx.view.collection.reset( response );                              
    },ctx ) );

collection.reset(data)我用来重新初始化集合的要点

于 2012-11-13T09:52:54.017 回答
2

如果您想继续为 Promise 获取“thenable”,那么您也可以执行以下操作:

fetch: function() {
    var self = this,
        deferred = new $.Deferred();

    $.get(this.url).done(function(data) {
            // parse data
        self.reset({parsed data});
        deferred.resolve(); //pass in anything you want in promise
     });
     return deferred.promise();
}
于 2014-06-13T00:09:47.857 回答
0

如果您需要为每个模型和/或集合执行此操作,请覆盖Backbone.ajax.

覆盖Backbone.ajax为您提供options通常会传递给$.ajax. 您只需要返回$.ajax(或其他Promise)的响应,而无需担心在集合/模型中设置内容。

于 2017-02-08T06:51:57.967 回答