Search code examples
javascriptfunctionprototypejs

Referencing a Prototype.js function from a function inside 'initialize'


In the following JavaScript code, from inside function(elem) {..., how do I reference the reachMe function ? I am just trying to attach a listener to elem so that reachMe gets called when elem gets clicked.

If I replace whatHereToMeanTheReachMeFunction with this it doesn't work because there this is the window object. If instead I put reachMe there I get the error Uncaught TypeError: Cannot read property 'bindAsEventListener' of undefined.

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

}

Solution

  • I made a few tweaks to your code and hopefully this will help you out

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