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)
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)