在javascript对象之间创建侦听器

在javascript对象之间创建侦听器,javascript,events,Javascript,Events,我在使用Mootools,我有两个类(class1,class2),class2在class1中使用 class2获取两个方法(func1,func2) func1用于显示元素,并在class1中调用 当单击func1显示的元素时,使用func2 如果func2被调用,我想在类1中得到一个事件,但我不知道如何调用 谢谢你的帮助 编辑:一些代码示例 var Class1 = function(){ var class2 = new Class2(); class2.func1();

我在使用Mootools,我有两个类(class1,class2),class2在class1中使用

class2获取两个方法(func1,func2)

func1用于显示元素,并在class1中调用

当单击func1显示的元素时,使用func2

如果func2被调用,我想在类1中得到一个事件,但我不知道如何调用

谢谢你的帮助

编辑:一些代码示例

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
    }

} 
看一看关于创建和触发事件的内容

基本上可以执行以下操作:

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);
    }

}    
你是说这个

var Class1 = function(){
    var class2 = new Class2();
    class2.func1();
    class2.onElementsHide(function(){
        alert('elements are invisibles !!')
    });
}

var Class2 = function(){

    this.cb = function(){};

    this.func1 = function(){
        //show elements
        elementOnClick(this.func2)
    }

    this.func2 = function(){
        //hide elements
        this.cb(); //<<Added
    }

    this.onElementsHide = function(callback){
        //trigger callback when func2 is used
        this.cb = callback; /// <<Added
    }

} 
var Class1=函数(){
var class2=新的class2();
class2.func1();
class2.onElementsHide(函数(){
警报('元素不可见!!')
});
}
var Class2=函数(){
this.cb=函数(){};
this.func1=函数(){
//显示元素
elementOnClick(this.func2)
}
this.func2=函数(){
//隐藏元素

this.cb();//当您还没有发布任何代码时,很难知道如何帮助您调整代码。您能添加一小段问题代码并说出哪些行不符合您的要求吗?我添加了一些代码来解释,我想知道在调用finch时如何在onElementsHide中触发回调。请输入“this.onElementsHide()”在这个.func2()中,以及在这个.onElementsHide()中的“callback()”。@dandavi很抱歉,我不太明白,如果我把这个.onElementsHide()放在这个.func2()中,类中不会触发任何东西。在这种情况下,回调将在使用onElementsHide后直接执行,我想在执行func2时触发回调