0

我对 Backbone.js 和 Require.js 很陌生。在我的应用程序中,我通过 require (使用文本!插件)将模板加载到每个模块中,如下所示:

define([
'jQuery',
'Underscore',
'Backbone',
'API',
'Utils',
'text!templates/home/register.html'
], function($, _, Backbone, api, utils, registerTpl){
       var registerView = Backbone.View.extend({
           el: $("#content"),
           render: function(){
               this.el.html(registerTpl);
           },
           {...}

我不知道如何绑定数据模型或直接将数据加载到我的模板中,如backbonetutorials.com 示例中所示,如下所示:

{...}
render: function(){
        //Pass variables in using Underscore.js Template
        var variables = { search_label: "My Search" };
        // Compile the template using underscore
        var template = _.template( $("#search_template").html(), variables );
        // Load the compiled HTML into the Backbone "el"
        this.el.html( template );
},
{...}
<script type="text/template" id="search_template">
<!-- Access template variables with <%= %> -->
<label><%= search_label %></label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>

任何见解、提示或代码片段将不胜感激。

4

1 回答 1

3

这很简单,在本教程中,它直接从 DOM 获取模板数据,而您将其作为引用传递给 require js。

你可以这样做:

template = _.template(registerTpl),

render: function(){
        var variables = { search_label: "My Search" };
        this.el.html(this.template(variables));
        return this;
},

相反,如果您想将模型的数据与模板一起使用:

this.el.html(this.template(this.model.toJSON()));   
于 2012-10-05T12:57:42.523 回答