我找了两件事情更好的解决方案:
我如何能理解如果数据取出,并准备好了,我用BasicDealList.on("reset", function(){})
以了解如果数据是从阿贾克斯获取和分析,并随时可以使用,但感觉很脏。
如果空的JSON来自读取诸如{}
它仍然显示BasicDealList.length为1,而它应该是0从而我被迫检查第一元件是经由空collection.length == 1 && jQuery.isEmptyObject(BasicDealList.toJSON()[0]
这是非常难看。
下面是代码:
BasicDeal = Backbone.Model.extend();
BasicDealCollection = Backbone.Collection.extend({
model: BasicDeal,
url: '/some/ajax/url/',
});
BasicDealList = new BasicDealCollection();
BasicDealList.on("reset", function(collection, response){
isEmpty = collection.length == 1 && jQuery.isEmptyObject(BasicDealList.toJSON()[0]);
if (isEmpty){
// render no deal found html
}
else{
// render list of deals
}
}
BasicDealList.fetch();
如果你不喜欢听的reset
,你可以直接传递一个回调.fetch()
BasicDealList.fetch({
success: function(collection, response){
// ...
}
});
如果,以后在你的应用程序,你想知道你是否已经获取的数据,你可以平时只检查BasicDealList.length
。 如果你希望避免的藏品是实际上空的服务器上的一再要求,你可能需要制定出一个定制的解决方案,例如在设置一个标志.fetch()
BasicDealList.fetch({
success: function(collection, response){
BasicDealList.fetched = true;
// ...
}
});
至于空数据问题,您应该返回[]
从服务器,而不是{}
骨干收集调用this.add(models, ...)
内.reset()
和.add()
检查是否models
参数为数组; 如果它不是,它把它封装在一个:
models = _.isArray(models) ? models.slice() : [models];
因此,通过{}
将导致models
设定为[{}]
这是不是你想要的。 如果你无法控制的服务器,你可以做的检查{}
在自定义.parse()
方法,返回[]
如果它的发现。
我知道这个问题已经回答了,但这里是一个另类。
BasicDealCollection = Backbone.Collection.extend({
model: BasicDeal,
url: '/some/ajax/url/',
});
myCollection = new BasicDealCollection()
deferred = myCollection.fetch()
$.when(deferred).then(function() {
// do stuff when we have the data.
});
这样做的主要好处是,我们使用的是“何时”的功能。 “何时”的功能使我们能够检查多个取电话和做一个成功的能力。
$.when(deferredOne, deferredTwo, deferredThree).then(function() {
// do stuff when we have the data.
});
此外,如果我们存储递延对象到一个变量,我们可以做这样的事情。 变量将是一个标志,让我们知道,我们已经加载的数据。
if (deferred.state() === "resolved") {
// do stuff when we have the data.
}
当我们调用fetch()方法对集合返回一个jQuery Deferred对象。 这个jQuery Deferred对象可以在3种状态,“待定”,“拒绝”或“已解决”一旦我们拥有的数据,它将设置延迟对象的状态来解决。
我们需要一种方法来判断一个RelationalModel的关系已被提取或不。 这是我们的解决方案(在CoffeeScript中)。
initialize: (objects, options) ->
@fetched = false
@listenTo @, 'sync', -> @fetched = true
文章来源: Backbone.js: Elegant way to check if data ready and if the dataset is empty