为了简单起见,我应该这样做
$(@el).html @template(model: @model)
或者
$(@el).html @template(@model.toJSON())
我曾经走第一种方式,这就是我被教导的方式。但最近我发现第二种方式也可以接受。它至少在渲染模板时节省了很多 @model.get("attribute_name") 。
那么最好的方法是什么?
为了简单起见,我应该这样做
$(@el).html @template(model: @model)
或者
$(@el).html @template(@model.toJSON())
我曾经走第一种方式,这就是我被教导的方式。但最近我发现第二种方式也可以接受。它至少在渲染模板时节省了很多 @model.get("attribute_name") 。
那么最好的方法是什么?
I think @model.toJSON()
is better, for the reason you've mentioned: it makes for cleaner templates.
This:
<div><%= name %></div>
Is easier on the eyes than:
<div><%= this.model.get("name") %></div>
Look at some of the example apps on Backbone.js, you'll see they use the .toJSON()
approach.
I suppose it's also a question of whether you want your templates to have access to the full View object. Obviously, that is not possible once you use toJSON()
. To me, not having that access is a plus respecting the separation of concerns, since the template should be about presentation, with minimal code, and appearing as close to regular HTML markup as possible.