Dubbed events in OOP in Javascript

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.

+4
source share
1 answer

I would have thought that the event should be rewritten.

No, it will not be overwritten. He adds them and fires them (see addEventListener , which is behind the on function).

You must add an event once. Your decision is correct.

Here is the essence of the problem (see comments):

 myObject.prototype.change = function () { var box = this.container; console.log(box); box.find('button').on( 'click', // Here you create a new function object. // Each time you call the `change` method, // it will add another function object as an event handler. function () { console.log('firing'); box.find('p').toggle(); } ); }; 
+1
source

All Articles