2013-03-31 26 views
0

是的我是新來的JS和backbonejs。這在backbone.js中的奇怪行爲控制器

讓我們現在深入研究這個問題。

我在backbonejs Controller中有一個非常奇怪的行爲this

這裏是我的控制器

var controller = Backbone.Controller.extend({ 
    _index: null, 

    routes: { 
     "": "index"     
    }, 


    initialize: function(options){ 

     var self = this; 
     if (this._index === null){ 

      $.getJSON('data/album1.json',function(data) { 
       //this line is working self._index is being set 
       self._index = new sphinx.views.IndexView({model: self._photos}); 
      }); 
      Backbone.history.loadUrl(); 
     } 

    }, 

    index: function() { 
     //this line is not working 
     //here THIS is pointing to a different object 
     //rather than it was available through THIS in initialize method 
     this._index.render(); 
    } 

}); 

下面的代碼是在文件的結尾到啓動控制器。

removeFallbacks(); 
gallery = new controller; 
Backbone.history.start(); 

現在,我失去了一些東西。但什麼? 如果這是錯誤的方式什麼是正確的方式? 我需要訪問我設置的屬性初始化方法從索引方法。

它看起來像索引方法正在改變它的範圍的來電功能。 我需要保留這個範圍。

+0

@muistooshort其實我下面的[Jquerys最好的朋友(http://addyosmani.com/blog/building-spas-jquerys-best-friends/)教程。 –

+2

我推薦了一個更新的教程,Backbone從0.5版本開始就沒有'Backbone.Controller',並且在2011年7月就出現了。從0.5開始,有很多很小的變化(不是很小)學習這樣一箇舊版本只會妨礙你的發展。此外,jQuery的模板系統已被棄用,不再被支持。 –

回答

0

您必須將路由動作指定到骨幹路由而不是控制器。路由器內部是您要初始化控制器和視圖的位置。

另外,沒有方法Backbone.history.loadURL()。我認爲你應該使用Backbone.history.start(),然後調用路由器實例中的導航,例如router.navigate('state or URL');

var myApp = Backbone.Router.extend({ 
    _index: null, 

    routes: { 
     "": "index"     
    }, 

    initialize: function(options){ 
     //Initialize your app here 
     this.myApp = new myApp(); 
     //Initialize your views here 
     this.myAppViews = new myAppView(/* args */); 

     var self = this; 
     if (this._index === null){ 

      $.getJSON('data/album1.json',function(data) { 
       //this line is working self._index is being set 
       self._index = new sphinx.views.IndexView({model: self._photos}); 
      }); 
      Backbone.history.loadUrl(); //Change this to Backbone.history.start(); 
     } 

    }, 

    // Route actions 
    index: function() { 
     this._index.render(); 
    } 
});