Javascript Backbone.js:检查数据是否准备就绪以及数据集是否为空的优雅方式
我正在为两件事寻找更好的解决方案:Javascript Backbone.js:检查数据是否准备就绪以及数据集是否为空的优雅方式,javascript,backbone.js,Javascript,Backbone.js,我正在为两件事寻找更好的解决方案: 如何理解数据是否已提取并准备就绪,我使用BasicDealList.on(“reset”,function(){})来理解数据是否已从ajax提取并解析并准备就绪,但感觉脏了 如果一个空的JSON来自于获取,比如{},它仍然显示BasicDealList.length为1,而它应该为0,因此我不得不通过collection.length==1&&jQuery.isEmptyObject(BasicDealList.toJSON()[0]检查第一个元素是否为空
- 如何理解数据是否已提取并准备就绪,我使用
来理解数据是否已从ajax提取并解析并准备就绪,但感觉脏了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();
如果您不喜欢侦听
重置
,可以直接将回调传递到.fetch()
:
如果以后在应用程序中,您想知道是否已经获取了数据,通常只需检查BasicDealList.length
。如果您想避免重复请求服务器上实际为空的集合,您可能需要制定自定义解决方案,例如在.fetch()上设置标志
:
至于空数据问题,您应该从服务器返回[]
,而不是{}
。主干网的集合调用这个。在.reset()
中添加(models…)
,并且.add()
检查models
参数是否是数组;如果不是数组,则将其封装在一个数组中:
models = _.isArray(models) ? models.slice() : [models];
因此,传递
{}
将导致模型
设置为[{}]
,这不是您想要的。如果无法控制服务器,您可以在自定义.parse()
方法中检查{}
,返回[]
如果找到了。我们需要一种方法来判断RelationalModel的关系是否已被提取。这是我们的解决方案(在Coffeescript中)
我知道这个问题已经得到了回答,但这里有一个选择
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”函数,“when”函数使我们能够检查多个fetch调用并执行一次成功
$.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延迟对象。jQuery延迟对象可以处于3种状态,“挂起”、“拒绝”或“已解决”。一旦我们有了数据,它会将延迟对象的状态设置为已解决。非常感谢您的详细解释!
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.
}