PDA

View Full Version : Resolved Storing event methods in button 'data' attribute - Listeners shortcut OOP approach



crobinson42
12-22-2013, 09:27 PM
I'm fascinated with a shortcut for javascript apps and event listeners - i'd like to share this with everyone (newbies especially)!

On your page you have several buttons:


<button class="add">Add</button>
<button class="update">Update</button>
<button class="delete">Delete</button>


Then you have listeners (I use jQuery):


$('button.add').click(function(){
//do something
});
$('button.update').click(function(){
//do something
});
$('button.delete').click(function(){
//do something
});


^^^ This can add up to be a lot of code and messy - here's an OO approach to listeners:

Add data attribute to your buttons:


<button data-method="add">Add</button>
<button data-method="update">Update</button>
<button data-method="delete">Delete</button>


Now, in your javascipt you want to write less listener code so you check for the data-method value and call that method:


//listener for all button clicks
$('button').click(function(){

var method = $(this).data('method');//get the method/action of the button being clicked

buttonEvents[method]();//call the method of the button in the "buttonEvents" object by the key
});

var buttonEvents = {
add: function(){
//do something
},
update: function(){
//do something
},
delete: function(){
//do something
}
};


There you have it! shortening up the listener code in a jiff!

Bullets
The 'buttonEvents' object is the scope you are calling the key/variable expression. Because of this, you do not user the '.' instead use '[]' similar to an array (arrays and objects are very closely related)

traq
12-22-2013, 09:42 PM
Very nice. data-* attributes are underrated.

Minor suggestion:
var method = $(this).data('method');//get the method/action of the button being clicked
You don't have to create a jQuery object, here: it's expensive, and there's no advantage over "vanilla" js. This line could be:
var method = this.getAttribute( 'data-method' );
Of course, you don't need to use jQuery to assign the event listener, either, but that takes care of some complexity in making things work cross-browser.