2017-05-18 72 views
-1

就拿這個例子中,使用了「widgetManager」對象事件綁定到所有手風琴的Javascript:使用綁定,而不會覆蓋此

widgetManager = { 
    name : 'widgetManager', 
    initiate : function(){ 
     $('.accordion').accordion({ 
      onClosing : this.onCloseAccordion.bind(this.name), 
     }) 
    }, 
    onCloseAccordion : function(){ 
     console.log(name); //I want the event to receive the manager name 
     console.log(this); //But still be able to know which accordion was clicked 
    } 
} 
widgetManager.initiate(); 

如果我綁定的東西手風琴的onClosing事件時,它就會失去參照本身(即將關閉的手風琴),但我也需要一種方法來將'name'屬性傳遞給函數。

也許bind不是我要找的,但有沒有一種簡單的方法來解決這個問題?

我想一個更好的措辭是,如何將一個對象傳遞給函數不會覆蓋功能的示波器的this

我使用語義UI的手風琴是否有幫助或改變任何東西,但該事件沒有參數https://semantic-ui.com/modules/accordion.html#/settings

+0

如果您認爲問題是重複的或需要改進,請告訴我,讓 – Mojimi

+0

應該'this.onCloseAccordion'是'this.onClosing'? – Barmar

+0

@Barmar你說得對,我的錯誤,謝謝! – Mojimi

回答

1

您可以簡單地參考widgetManager.name來獲取名稱。

widgetManager = { 
    name : 'widgetManager', 
    initiate : function(){ 
     var theManager = this; 
     $('.accordion').accordion({ 
      onClosing : this.onCloseAccordion.bind(this), 
     }) 
    }, 
    onClosing : function(){ 
     console.log(widgetManager.name); //I want the event to receive the manager name 
     console.log(this); //But still be able to know which accordion was clicked 
    } 
} 
widgetManager.initiate(); 

如果你想要更通用的東西,你應該使用構造函數來創建不同的管理器。

function widgetManager(name) { 
    this.name = name; 
    this.initiate = function() { 
     $('.accordion').accordion({ 
      onClosing: this.onCloseAccordion.bind(this); 
     }); 
     return this; // For fluent interface 
    }; 
    this.onCloseAccordion = function() { 
     console.log(name); 
     console.log(this); 
    }; 
}; 

然後你使用這樣的:

var theWidgetManager = new widgetManager("widgetManager"); 
theWidgetManager.initiate();