0

我正在构建一个主干应用程序并偶然发现了一个麻烦。在第一次加载模板加载正常,但在路由器导航我得到参考错误。

这是代码:

模板:

<script type="text/template" id="testTpl">
        <div class="cabinet">
            Its a test! <%= userName %>.
            <a href="#/">Go back</a>
        </div>        
    </script>

<script type="text/template" id="secondTpl">
        <div class="cabinet">
            Its a second test! <%= test %>.
            <a href="#/">Go back</a>
        </div>        
    </script>

路由器:

var Controller = Backbone.Router.extend({
    routes: { 
        "!/test": "test", 
        "!/second": "second"
    },
    test: function () {
        if (Views.Test!= null) {
            Views.Test.render();
        }
    },
    second: function () {
        if (Views.Second!= null) {
            Views.Second.render();
        }
    }
});

意见:

var Block = Backbone.View.extend({
    render: function (options) {
    var userName = {userName:'success!', test: 1};
    var tpl = _.template(this.options.template);
        $(this.el).html(tpl(userName));
    }
});

Views = { 
            Test: new Block({el:$('#block'), template: $('#testTpl').html()}),
            Second: new Block({el:$('#block'), template: $('#secondTpl').html()})
        };

在第一次加载时,一切正常,模板加载变量,但在那之后,跟随 # 链接导致

Uncaught ReferenceError: userName is not defined

这里可能出了什么问题?为什么直接做一个对象

userName = {userName:'success!', test: 1}

并在模板中使用它会破坏应用程序?

4

1 回答 1

0

首先,在 1.1 中,Backbone 视图不再将 options 参数作为 this.options 自动附加。

所以你的代码与最新的 Backbone 不兼容。要修复它,只需在视图的“初始化”功能中添加一些代码:

initialize: function ( options ) {
    this.template = options.template;
}

在此之后,我在这里测试了您的代码:http: //jsfiddle.net/RS88E/1/ 一切似乎都很好。

于 2013-10-28T01:17:59.697 回答