在对象javascript之间创建监听器

时间:2014-01-21 20:24:23

标签: javascript events

我正在使用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
    }

} 

2 个答案:

答案 0 :(得分:1)

查看有关创建和触发事件的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);
    }

}    

答案 1 :(得分:1)

你是说这个?

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
    }

}