检查骨干js中是否有某个模型或集合

nep*_*eph 27 javascript backbone.js

当您覆盖骨干同步时,模型/集合.save()/ fetch()都使用相同的骨干同步方法,那么检查Backbone.sync接收的模型或模型集合的最佳方法是什么?

举个例子:

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
}
Run Code Online (Sandbox Code Playgroud)

我想我正在寻找一个"安全"的最佳实践,我当然可以检查某些属性或方法,只有模型或集合有,但似乎是hackish,不应该有更明显的方法吗?而且我可能找不到它.

谢谢!

小智 56

你也可以尝试instanceof这样:

Backbone.sync = function(method, model, options) {
  if (model instanceof Backbone.Model) {
    ...
  } else if (model instanceof Backbone.Collection) {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*zol 10

@ 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
Run Code Online (Sandbox Code Playgroud)