我想以非 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的新手,谢谢大家!
如果要将自定义"装饰器"添加到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
另外,如果你想使用Backbone的fetch
方法返回的jQuery承诺,不要忘记最后一行的return
。
有关更多详细信息,请参阅 http://japhr.blogspot.in/2011/10/overriding-url-and-fetch-in-backbonejs.html。
主干集合有两种方法来设置新数据的添加和重置。假设您要将所有集合数据替换为传入数据,因此使用重置:
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)
}
});
}
})
我正在使用这样的东西:
$.when( $.ajax( URL, { dataType: "json" } ) )
.then( $.proxy( function( response ) {
ctx.view.collection.reset( response );
},ctx ) );
我使用collection.reset(data)
来重新初始化集合的要点
如果你想继续获取承诺的"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();
}
为每个模型和/或集合执行此操作,请覆盖Backbone.ajax
。
覆盖Backbone.ajax
会为您提供通常传递给 $.ajax
的请求options
。 您只需要返回$.ajax
(或其他一些Promise
)的响应,并且无需担心在集合/模型中设置内容。