2017-05-18 48 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();