我正在使用 Mootools,并且我有两个类(class1、class2),class2 用于 class1
class2获取两个方法(func1,func2)
func1用于显示元素,在class1中调用
func2 用于单击 func1 显示的元素之一。
如果调用 func2,我想在 class1 中获取一个事件,但我不知道如何实现。
感谢您的帮助。
编辑:一些代码示例
var Class1 = function(){
var class2 = new Class2();
class2.func1();
class2.onElementsHide(function(){
alert('elements are invisibles !!')
});
}
var Class2 = function(){
this.func1 = function(){
//show elements
elementOnClick(this.func2)
}
this.func2 = function(){
//hide elements
}
this.onElementsHide = function(callback){
//trigger callback when func2 is used
}
}
最佳答案
看看MDN's article关于创建和触发事件
基本上执行如下操作:
var Class1 = function(){
var class2 = new Class2();
class2.func1();
class2.onElementsHidden(function(){
alert('elements are invisibles !!')
});
}
var Class2 = function(){
//Create a custom event
var ElementsHiddenEvent = new Event("ElementsHidden");
this.func1 = function(){
//show elements
elementOnClick(this.func2)
}
this.func2 = function(){
//hide elements
//Dispatch the event
document.dispatchEvent(ElementsHiddenEvent);
}
//Sets a listener for the event
this.onElementsHidden = function(callback){
//make sure the callback is a function
if(typeof(callback)!=="function") return;
//Set a listener for the custom event, and set it to execute callback
document.addEventListener("ElementsHidden",callback);
}
}
关于javascript - 在对象之间创建监听器 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21268360/