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!
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.targetis if you programatically want to call it bydiv.fireEvent("click")which will fail as the event won’t be passed on. but you can dodiv.fireEvent("click", { target: div });and get around thatof course, since div is a scoped hoisted variable you already have, you can just do: