I’m trying to define a click handler in a Mootools class. My handler presumes opening a block of links, each of which should be ‘equipped’ with its own click handler, which should trigger a link specific action. What I mean is let’s suppose I have the following HTML code:
<div id="wrapper">
<a href="#" id="header">open options</a>
<div class="optionsBlock" style="display:none">
<a href="#">1</a>
<a href="#">2</a>
<a href="#">3</a>
</div>
</div>
Then I’m trying to define a class like this in Mootools:
var myHandler = new Class({
Implements : [Events],
initialize : function(element){
this.element = document.id(element);
this.elements = this.element.getChildren('a');
this.elements.addEvents('click', function(ev){
ev.preventDefault();
//'this' as a reference to the current element in the array, which is being clicked, correct?
this.getSibling('div.optionsBlock').setStyle('display', 'block');
var parentLink = this;
this.getSibling('div.optionsBlock').getChildren('a').addEvent('click', function(e){
e.preventDefault();
//should append the text of currently clicked link into the parent link
parentLink.appendText(this.get('text'))
});
});
}
});
new myHandler('wrapper');
This is just an illustration of how I can imagine the code should be like (and I’m sure this code is not good at all), but I really need some help regarding the following:
-
Since adding new events constatly changes the scope of ‘this’, how should I keep a reference both to the class instance and the element being clicked?
-
How should I modify the class in order not to have the entire code inside the initialize method? I tried to create separate methods for every event handler, but as a result I got confused with the scope of ‘this’, with binding and trying to get all of this together really annoys me, but I want to get a grip of this knowledge.
-
How to keep track of the scope of ‘this’ when adding nested event handlers inside a class? I honestly googled and searched for an answer but for no avail.
Thanks!
scope, take your pick – asked many many times – search here for
[mootools]scope this:Mootools class variable scope
mootools variable scope
Mootools – Bind to class instance and access event object
to recap:
var self = this;then referenceself.propor use thefn.bindpatternattachEvents: function() {}and have initialize call that.