2012-02-02 42 views
1

我正在使用jquery droppable的backbone.js。在'綁定'觸發器中傳遞變量

我遇到的問題是,在進入.droppable功能,「這個」不再指骨幹對象。我讀過耶胡達卡茲關於理解「這個」的文章,但我仍然不明白如何「解決」這個問題。 http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

我認爲出問題的方法是隻綁定模型更改事件觸發一個方法,但我需要傳遞一個變量給該方法,我不知道該怎麼做。

這裏是我的代碼的摘錄。在線MyApp.User.Trigger('new_class');,有沒有辦法添加一個變量?我如何把它在綁定事件?

initialize: function(){ 
    user = MyApp.User; 
    MyApp.User.bind('new_class',this.save, this); 
    this.render(); 
}, 

render: function(){ 

    $('li.empty').droppable({ 

     hoverClass: "ui-state-active", 
     start: function(e){ 
      $(this).click('unbind'); 
     }, 
     drop: function(event, ui){ 
      var add_class_to_user = $(this).attr('data-id'); 
      MyApp.User.Trigger('new_class'); 
     } 
    }) 

}, 

save: function(class){ 
    var add_class = new Myapp.Model.Class({ 
     class_id: class, 
     user_id: user.id 
    }); 
    add_class.save() 
} 

回答

4

我不知道我理解你的要求, 所以我會回答這兩個:

在這樣的背景下:

,爲什麼你不存儲引用這個到一個新的變量?

... 

render: function(){ 
    // here we put this in a new variable myView. 
    var myView = this; 

    $('li.empty').droppable({ 
     hoverClass: "ui-state-active", 
     start: function(e){ 
      $(this).click('unbind'); 

      // here you can use myView instead of this, if you want something from your view. 
      myView.model.set({'name', 'newname'}); 

     }, 
     drop: function(event, ui){ 
      var add_class_to_user = $(this).attr('data-id'); 
      MyApp.User.Trigger('new_class'); 
     } 
    }) 
}, 

... 

上的參數傳遞到事件

... 

render: function(){ 
    $('li.empty').droppable({ 
     hoverClass: "ui-state-active", 
     start: function(e){ 
      $(this).click('unbind'); 
     }, 
     drop: function(event, ui){ 
      var add_class_to_user = $(this).attr('data-id'); 
      MyApp.User.Trigger('new_class', add_class_to_user); 
     } 
    }) 
}, 

... 

在用戶模式,當然,你應該這樣做的問題:(或更可能在另一種觀點認爲,可以綁定到該事件在用戶模型)

MyApp.User.bind('new_class', function(myparameter) { 
    alert('yay, my parameter is:' + myparameter); 
    $('#myElement').addClass(myparameter); 
}); 

在jsfiddle中的示例:可以在這裏找到.... http://jsfiddle.net/saelfaer/MWuHj/

+0

感謝桑德,我去了添加事件給用戶的模式,因爲我同意這可能是做正確的方式。 – pedalpete 2012-02-02 15:04:05

+0

嗯,這正是我的意思,你可以觸發用戶的事件,但你可以從任何地方綁定到它,通常你不會綁定在用戶本身,如果你想在DOM中的類改變,因爲DOM是視圖的響應性,所以UserView可以綁定到他的用戶模型併爲你添加類... – Sander 2012-02-02 15:18:40