When using backbone.js and the companion template template engine underscore, I noticed that most examples call model.ToJSON() when rendering instead of just passing model . I understand that my template will have to change the way data is received.
I wonder why and what benefit we get from toJSON ()?
Typical example
In a typical example, model.ToJSON() is called when rendering. Note that for brevity, I put the template as a string literal.
ToDoItemView = Backbone.View.extend({ template : _.template( '<li><%=ToDoNote%></li>'), render : function () { var out= this.template(this.model.toJSON());
Alternative method
I dug trunk 0.9.2 and underlined code 1.3.3. In the spine, we noticed that model.ToJSON() does the following: _.clone(this.attributes) . Inside the template rendering engine, my compiled template calls the passed data obj.
After looking at these snippets, I realized that attribute cloning is not required. Instead, I can directly pass my model (albeit with some syntax changes in the template). Something like...
ToDoItemView = Backbone.View.extend({ /* other viewey stuff */ template : _.template( '<li><%=obj.get('ToDoNote')%></li>'), //<--notice GET() render : function () { var out= this.template(this.model); //<-- look ma no json $(this.el).html( result ) } return this; } }); //end view
Looking at two examples, the only reasons I can come up with for a call in JSON are:
- protect model data from vile representation
- the view locally changes the data (not a good idea in my opinion),
- view, you must access the values ββusing the syntax array / string (
obj[ namepart + someindex] )
My question boils down to: why would I have to call toJSON() and delete to clone properties, and not just use get () in my templates?
EBarr
source share