And Finally
And Finally

Reputation: 5704

Mootools: Events in element constructor

I'm creating a new element in Mootools which has events, thus:

var div = new Element('div', {
id: 'dynamic',
'class': 'injected',
styles: {
    color: '#f55'
},
html: 'Hong Kong Phooey, number one super guy. Hong Kong Phooey, quicker than the human eye. He\'s got style, a groovy style, and a car that just won\'t stop. When the going gets tough, he\'s really rough, with a Hong Kong Phooey chop (Hi-Ya!). Hong Kong Phooey, number one super guy. Kong Phooey, number one super guy. Hong Kong Phooey, quicker than the human eye. He\'s got style, a groovy style, and a car that just won\'t stop. When the going gets tough, he\'s really rough, with a Hong Kong Phooey chop (Hi-Ya!). Hong Kong Phooey, number one super guy.',
events: {
    click: function(event) {
        alert('clicked');
    },
    mouseenter: function(event) {
        var self = $('dynamic');
        self.setStyle('color', '#090');
    },
    mouseleave: function(event) {
        var self = $('dynamic');
        self.setStyle('color', '#f55');
    }
}
});

div.inject(document.body);

Is it a bad technique to get the div with self = $('dynamic') in each event? I've tried

mouseenter: function(event) {
        this.setStyle('color', '#090');
    }.bind(this)

thinking that "this" would refer to the element I was constructing. But instead it refers to the global window.

Am I going about things the right way?

Thank you!

Upvotes: 1

Views: 344

Answers (2)

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

well - this in the context of the constructor before the actual element exists won't work, as you have discovered - it will scope window or anything bound up the scope chain from where you use the constructor.

having a selector self = selectorbyid is not very great either if you repeat it often and care about performance.

the fastest way to do this would be to reference event.target, which will be the div--or to break apart the element constructor in two and add the events when div is an object and you can bind it.

downside to using event.target is if you programatically want to call it by div.fireEvent("click") which will fail as the event won't be passed on. but you can do div.fireEvent("click", { target: div }); and get around that

of course, since div is a scoped hoisted variable you already have, you can just do:

mouseenter: function(event) {           
    div.setStyle('color', '#090');
},
mouseleave: function(event) {
    div.setStyle('color', '#f55');
}

Upvotes: 1

pleasedontbelong
pleasedontbelong

Reputation: 20102

you could use event.target

events: {
    mouseenter: function(event) {
        event.target.setStyle('color', '#090');
    },
    mouseleave: function(event) {
        event.target.setStyle('color', '#f55');
    }
}

Upvotes: 3

Related Questions