Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 560
neph Avatar asked Apr 18 '12 06:04

neph


People also ask

What is collections in Backbone JS?

Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

Why use Backbone js?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

How does Backbone js work?

Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.


1 Answers

You could also try instanceof like so:

Backbone.sync = function(method, model, options) {   if (model instanceof Backbone.Model) {     ...   } else if (model instanceof Backbone.Collection) {     ...   } } 
like image 68
fiskers7 Avatar answered Sep 21 '22 05:09

fiskers7