2013-10-28 25 views
0

我構建了一個主幹應用程序,並偶然發現了一個麻煩。 在第一次加載模板加載正常,但在路由器導航我得到參考錯誤。主幹第二次呈現的未捕獲ReferenceError

下面的代碼:

模板:

<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} 

並在模板中使用它打破應用程序?

回答

0

首先,在1.1中,Backbone Views不再具有作爲this.options自動附加的options參數。

所以你的代碼與最新的Backbone不兼容。要修復它只是添加一些代碼爲「初始化」視圖的功能:

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

在此之後我這裏測試代碼:http://jsfiddle.net/RS88E/1/ ,一切似乎是確定。