从内部函数引用Prototype.js函数'初始化'

时间:2015-10-05 15:01:54

标签: javascript function prototypejs

在以下JavaScript代码中,从function(elem) {...内部,我如何引用reachMe函数?我只是想将一个监听器附加到elem,以便在reachMe被点击时调用elem

如果我将whatHereToMeanTheReachMeFunction替换为this,则它不起作用,因为thiswindow对象。如果我把reachMe放在那里我得到错误 Uncaught TypeError:无法读取属性' bindAsEventListener'未定义的

var MyClass = Class.create();

MyClass.prototype = {

    initialize : function(spec) {

        $$('*[id^=prefix]').each(

            function(elem) {

                elem.observe('click', whatHereToMeanTheReachMeFunction.bindAsEventListener(this));
            }
        );
    },

    reachMe : function(event) {

        console.log("Here I am.");
    }

}

1 个答案:

答案 0 :(得分:2)

我对你的代码做了一些调整,希望这会帮助你

var MyClass = Class.create({
    //The class can be defined in one fell swoop
    initialize : function(spec) {
        $$('*[id^=prefix]').each(

            function(elem) {

                //you should only need normal bind() here
                elem.observe('click',this.reachMe.bind(this));
            },this
            //include 'this' here to set the context inside the each method
         );

        //you could also do the above action like this, 1 observer vs multiple
        document.on('click','*[id^=prefix]',this.reachMe.bind(this));

    },

    reachMe : function(event) {

        console.log("Here I am.");
    }

}