neph
neph

Reputation: 743

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!

Upvotes: 27

Views: 17103

Answers (5)

Kabir Sarin
Kabir Sarin

Reputation: 18526

I'm not entirely sure how I feel about this because it seems a bit hackish, but I can't exactly think of why it would be super bad at the moment.

Definitely simple, and faster than an "instanceof" check (I'm assuming you won't name any other functions "isBBModel/Collection" on your objects?)

Backbone.Model.prototype.isBBCollection = function() { return false; }
Backbone.Model.prototype.isBBModel = function() { return true; }
Backbone.Collection.prototype.isBBCollection = function() { return true; }
Backbone.Collection.prototype.isBBModel = function() { return false; }

Upvotes: 1

Nicolas Zozol
Nicolas Zozol

Reputation: 7038

@fiskers7's answer works with deep extension :

        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

Upvotes: 10

fiskers7
fiskers7

Reputation: 918

You could also try instanceof like so:

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

Upvotes: 56

Exploit
Exploit

Reputation: 108

You could do something like this.

Backbone.Model.prototype.getType = function() {
    return "Model";
}

Backbone.Collection.prototype.getType = function() {
    return "Collection";
}

if(model.getType() == "Model") {}
if(model.getType() == "Collection"){}

Upvotes: 0

robrich
robrich

Reputation: 13205

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.

Upvotes: 2

Related Questions