Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get backbone model attributes without .get

In backbone it seems that I have to get model attributes via model.get('att_name')

I'd prever to get them the way I'd get any public field within an object: model.att_name

Can anyone think of a way to get around this?

eg: In python world I would override getattr on the model something like this:

def getattr(self, att):
   return self.get(att)

Oh, and I'm using CoffeeScript

like image 752
Adam Fraser Avatar asked Mar 08 '12 16:03

Adam Fraser


People also ask

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)

Does backbone need jQuery?

You can use the Backbone. Model without jQuery, but Backbone.

Does anyone use Backbone JS?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.


2 Answers

Model attributes that you use get() and set() or defaults to get/set are stored in the instance.attributes attribute.

Also, these are the attributes that are going to be passed to and returned from sync() as well as toJSON(). So when you fetch(), save() etc, only what is stored in instance.attributes gets passed along.

Nothing will stop you of course from having normal attributes like instance.foo on your objects. If you want to treat those as the other attributes and pass these along to fetch() and save() you can do so by providing a custom parse() on your model which by default does nothing. That said, you should only do this if you really deem it absolutely necessary, if only to comply to the Backbone conventions.

like image 61
ggozad Avatar answered Oct 07 '22 15:10

ggozad


The attributes are accessible at Model.attributes. You can read directly from that, but use set to change them. You can also get a representation of all your attributes from Model.toJSON() (note: toJSON() doesn't actually return JSON, but a javascript object).

The recommended way is to use toJSON() for templates, serialization etc.

like image 24
Linus Thiel Avatar answered Oct 07 '22 13:10

Linus Thiel