Backbone / Underscore template - when rendering, why call JSON?

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({ /* other viewey stuff */ template : _.template( '<li><%=ToDoNote%></li>'), render : function () { var out= this.template(this.model.toJSON()); //<--JSON $(this.el).html( out) } return this; } }); //end view 

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?

+7
source share
2 answers

Perhaps the following makes sense:

  • Interpolation instead of estimation is a big cost. So your version of the template is actually much slower than calling toJSon() and using evalution.

  • Logic refers to representations, not patterns. Representation of js-code (and the need for interpolation) in templates should be performed only if necessary.

  • You could argue that you should skip model.attributes instead of model.toJSON() , avoiding cloning. I assume that the reason is not to prevent the template from changing the attributes of the model. Alternatively, you can usually increase the result of model.toJSON() other things that obviously you don't want to do on model.attributes

+12
source

The likely reason is that the Backbone.js developers allowed you to use whatever template engine you want, and many template modules work with simple javascript objects, not Backbone Models.

+2
source

All Articles