2014-02-11 31 views
0

如何從不同視圖訪問變量?如何從不同視圖訪問變量?

我要訪問selectedColor在另一種觀點認爲:

'onClickColor': function(e) { 

     var view = this, 
      selectedColor = $(e.currentTarget).data('color'), //$(this).data('color'); 
      style = $('<style>.highlight { color: ' + selectedColor +'; margin-left: 4px;}</style>'); 

     $('.initial').css('color', selectedColor); 
     $('.highlight').css('color', selectedColor); 
     $('html > head').append(style); 
     //view.canvasColorPick(e); 
    }, 

然後在另一個看法,我想通過使用一個表單提交的ajax變量selectedColor。

 'formCollect' : function (e) { 

     var view = this; 
     var fname = $('#your_name').val(); 
     var email = $('#email').val(); 
     var state = $('#state').val(); 
     var color = selectedColor; 
     var url = 'services/users/add?name='+fname+'&email='+email+'&state='+state+'&color='+color+''; 
     $.get(url); 
    }, 

回答

0

它應該是最好的方式 - 訂閱一個視圖到另一個視圖的事件。既然你沒有提供範圍,你的視圖被實例化了,我假設它們都在全局範圍內。如果你不明白是什麼意思範圍請仔細閱讀本: What is the scope of variables in JavaScript?

所以假設實例化這樣你的第一個觀點:firstView = new FirstView();。第二個是secondView = new SecondView();

當firstView中的顏色發生變化時觸發事件:this.trigger("Color changed", {newColor: "black"});。請確保在觸發此事件之前兩個視圖都已實例化。

現在你需要訂閱secondView上的firstView的事件:secondView.listenTo(firstView, "Color changed", secondView.handleColorChanged);

這裏handleColorChanged是事件處理程序將獲得事件PARAMS作爲參數。

現在alltogeather:

var FirstView = Backbone.view.extend({ 
    /** your casual code here */ 
    'onClickColor': function(e) { 
    /** your code here */ 
    this.trigger("Color changed", { newColor: "black" }); 
    } 
}); 

var SecondView = Backbone.view.extend({ 
    /** your casual code here */ 
    'handleColorChanged': function(eventData) { 
    console.log(eventData); 
    } 
}); 

var firstView = new FirstView(), 
    secnodView = new SecondView(); 
secondView.listenTo(firstView, "Color changed", secondView.handleColorChanged); 

這不是解決你的任務只有一個辦法。但是,這是將觀點彼此分開的方式。沒有人知道另一個人在大型應用程序中最需要的東西,使調試過程變得簡單等等。

相關問題