Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

javascript - Backbone template method. Why are we passing in a model?

I can't figure out why we are passing in a model.toJSON() into this template:

app.TodoView = Backbone.View.extend({
  tagName: 'li',
  template: _.template($('#item-template').html()),
  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
    return this; // enable chained calls
  }
});

The example comes from this tutorial.

this.template(this.model.toJSON()) is the confusing part to me. The template method doesn't seem to take in an argument right? What is going on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Underscore _.template function takes a template string as argument (and optionally a settings object) and returns a new pre-compiled template function which takes an object as an argument.

This object is the data used within the template:

// creates a template function
var templateFunc = _.template("<span><%= name %></span>");

// render the template using the passed data
templateFunc({ name: "émile" }); // <span>émile</span>

By default, template places the values from your data in the local scope via the with statement. However, you can specify a single variable name with the variable setting.

_.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'});

model.toJSON() returns a shallow copy or the attributes hash of the model.

To achieve the equivalent of the above example:

var model = new Backbone.Model({ name: "émile" });
templateFunc(model.toJSON()); // <span>émile</span>

For Underscore.js before v1.7, the template function signature was a little different:

_.template(templateString, [data], [settings]) 

If a data object was passed, it didn't returned a function, but returned the rendered template string directly.

_.template('This is <%= val %>.', { val: "deprecated" });
// This is deprecated.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...