Check to see if something is a model or collection in backbone js
When you override backbone sync, both model/collection .save()/fetch() uses the same backbone sync method, so what is the best way to check if what Backbone.sync recieves is a model or a collection of models?
As an example:
Backbone.sync = function(method, model, options){
//Model here can be both a collection or a single model so
if(model.isModel()) // there is no isModel or isCollection method
}
I suppose I am looking for a "safe" best practice, I could of course check for certain attributes or methods that only a model or a collection have, but it seems hackish, shouldn't there be a better obvious way? And there probably is I just couldn't find it.
Thanks!
你也可以像这样尝试instanceof
:
Backbone.sync = function(method, model, options) {
if (model instanceof Backbone.Model) {
...
} else if (model instanceof Backbone.Collection) {
...
}
}
@ fiskers7的答案可以深入扩展:
var Item = Backbone.Model.extend({
className : 'Item',
size :10
});
var VerySmallItem = Item.extend({
size :0.1
});
var item = new Item();
var verySmall = new VerySmallItem();
alert("item is Model ?" + (item instanceof Backbone.Model)); //true
alert("verySmall is Model ?" + (verySmall instanceof Backbone.Model)); //true
This is equally hackish, but a Backbone collection has a model property, and a model doesn't -- it is itself a model.
Perhaps a safer method is model.toJSON() and see if the result is an object or an array. You're probably going to model.toJSON() in your custom Backbone.sync anyway, so though this is pretty computationally expensive, it would happen anyway.
链接地址: http://www.djcxy.com/p/67072.html上一篇: 骨干不能解析json
下一篇: 检查一下骨干js中是否有模型或集合