I know what is the problem but I don’t really understand why it is happening. Suppose you have this:
HTML:
<div><p>Hello</p><button>Fire</button></div>
<br/>
<button id="menu-button">Menu</button>
JavaScript:
function myObject(container, buttonElement) {
this.container = container;
}
myObject.prototype.change = function () {
var box = this.container;
console.log(box);
box.find('button').on('click', function() {
console.log('firing');
box.find('p').toggle();
});
};
var obj1 = new myObject($('div'));
$('#menu-button').on('click', function(){
obj1.change();
});
Fiddle: http://jsfiddle.net/L24As/1/
As you can see, when you click on the “Menu” button and obj1.change() starts, which adds an event handler to the button “Fire”, everything works as expected. However, if you click again on the “Menu” button, you are creating another event, so now toggle() doesn’t work because the first event is hiding and second one is showing the paragraph. Why is that? I would have thought that the event should have been overwritten.
I solved it like this:
function myObject(container) {
this.container = container;
this.change = function () {
var box = this.container;
console.log(box);
box.find('button').on('click', function() {
console.log('firing');
box.find('p').toggle();
});
};
}
var obj1 = new myObject($('div'));
obj1.change();
Is it a good solution? The event is attached to the button “Fire” since the start, so the “Menu” button is used to show other things, which makes them a bit different, although they perform the same task.
No, it wouldn’t be overwritten. It’s adding them and firing them all (see addEventListener which is behind the
onfunction).You should add the event once. Your solution is correct.
Here’s the essence of the problem (see the comments):