javascriptbackbone.jscoffeescript

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


Solution

  • 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.