I know what the problem is, but I really don't understand why this 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 press the Menu button and run obj1.change() , which adds an event handler to the Fire button, everything works as expected. However, if you press the Menu button again, you will create another event, so now toggle() does not work, because the first event is hiding, and the second shows this paragraph. Why is this? I would have thought that the event should be rewritten.
I solved it like this:
http://jsfiddle.net/L24As/3/
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();
This is a good decision? An event is attached to the Fire button from the very beginning, so the Menu button is used to display other things, which makes them a little different, although they perform the same task.
source share