在第二次渲染时,骨干未捕获的ReferenceError

时间:2013-10-28 00:17:07

标签: javascript backbone.js

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

以下是代码:

模板:

<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()})
        };

首次加载时,一切正常,模板加载变量,但之后,#links导致

Uncaught ReferenceError: userName is not defined

这里可能出现什么问题?为什么直接制作一个对象

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

并在模板中使用它打破了应用程序?

1 个答案:

答案 0 :(得分:0)

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

因此,您的代码与最新的Backbone不兼容。要修复它,只需添加一些代码来“初始化”视图功能:

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

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

相关问题