Search code examples
javascripteventsmootools

How do you access an object instance in the second parameter of the Mootools fireEvent function?


I'm working through Implements: [Events, Options] in Mootools.

I would like to pass a class property to the function that is called when an event fires. I would have thought that I could do it using this but this is undefined.

I have commented the code below where my problem is. I have a feeling that this might be to do with binding so I will be having a look at that now. Thanks in advance for any help!

var Person = new Class({

    Implements: [Options, Events],

    initialize: function(options){
        this.setOptions(options);
    }

});

greet = function(name){
    log('Hello, I am ' + name);
}

var ryan = new Person({
    name: 'Ryan',
    onArrive: greet //add event 'arrive'
});
ryan.fireEvent('arrive', ryan.options.name); //ideally I would use this.options.name?

This code works but it just seems strange to use the object instance name instead of this in the last line.


Solution

  • When you fire the event this is your instance of ryan. To make it work just make the following changes

    function greet(name){
        log('Hello, I am ' + this.options.name); //<-- use this here 
    }
    
    ryan.fireEvent('arrive');
    

    but since greet now depends on the instance it would be better to include it in your class definition

    var Person = new Class({
    
        Implements: [Options, Events],
    
        initialize: function(options){
            this.setOptions(options);
        },
        greet: function() { log('Hello, I am ' + this.options.name); //<-- use this here  }
    });
    

    and

    var ryan = new Person({
        name: 'Ryan',
        onArrive: this.greet.bind(this)  //or a function() { /* log('Hello,... */}
    });