2014-02-11 4 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"});이 발생합니다. 이 이벤트가 트리거되기 전에 두보기가 모두 인스턴스화되었는지 확인하십시오.

이제 firstView의 이벤트에 secondView 가입해야합니다 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); 

이 당신의 작업을 해결하는 유일한 방법은 아니다. 그러나 이것은 서로 견해를 분리하는 방법입니다. 아무도 큰 응용 프로그램에서 주로 필요한 것이 다른 디버깅 프로세스를 쉽게 알 수 있습니다.

관련 문제