Search code examples
javascriptbackbone.js

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!


Solution

  • You could also try instanceof like so:

    Backbone.sync = function(method, model, options) {
      if (model instanceof Backbone.Model) {
        ...
      } else if (model instanceof Backbone.Collection) {
        ...
      }
    }