2016-05-14 9 views
1

バックボーンのイベントシステムに問題があります。バックボーンlistenToはjquery関数をハンドラとして起動しません

jquery関数をコールバックとして直接渡すことはできますか?

次のコードないの火災の表示/非表示方法:

initialize: function() { 
    this.render(); 
    this.logoutButton = $('#logout-button'); 
    this.logoutButton.hide(); 
    this.listenTo(this.model, 'loginSuccessEvent', this.logoutButton.show); 
    this.listenTo(this.model, 'logoutSuccessEvent', this.logoutButton.hide); 
}, 

私はこれに変更した場合でも、それは完璧に動作します:fine manualから

initialize: function() { 
    this.render(); 
    this.logoutButton = $('#logout-button'); 
    this.logoutButton.hide(); 
    this.listenTo(this.model, 'loginSuccessEvent', this.showButton); 
    this.listenTo(this.model, 'logoutSuccessEvent', this.hideButton); 
}, 

showButton: function() { 
    this.logoutButton.show(); 
}, 

hideButton: function() { 
    this.logoutButton.hide(); 
} 

答えて

1

listenToobject.listenTo(other, event, callback)
[...]
objectは、コンテキストとして常にと呼ばれます。

だから、あなたがこれを言うとき:

this.listenTo(this.model, 'loginSuccessEvent', this.logoutButton.show); 

あなたが本当に言っている:

var show = this.logoutButton.show; 
this.listenTo(this.model, 'loginSuccessEvent', show); 

そしてバックボーンは、このようshow多かれ少なかれを呼び出します:

your_view.show(arg, ...); 
// Or internally: 
show.apply(your_view, arguments); 

だからshow(wh ichがjQueryのshow)が呼び出されると、そのthislogoutButtonではなく表示になります。 JavaScript関数内のthisは、関数が定義されている場所ではなく呼び出される方法に依存することに注意してください(もちろん、バインドされた関数を除く)。

あなたは、いくつかのオプションがあります。

  1. はあなたのshowButtonhideButton機能を使用してください。

  2. 無名関数を使用しますbound functionを使用し

    this.listenTo(this.model, 'loginSuccessEvent', function() { 
        this.logoutButton.show(); 
    }); 
    
  3. を:

    これで慎重に
    this.listenTo(this.model, 'loginSuccessEvent', this.logoutButton.show.bind(this.logoutButton)); 
    

    しかし、showlistenToは、通常、あなたが必要な場合があります使用することの引数で呼び出されますshowhideが期待していない引数を混同しないように、bindにもっと多くの引数を指定してください。

関連する問題