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:
Then you have listeners (I use jQuery):HTML Code:<button class="add">Add</button> <button class="update">Update</button> <button class="delete">Delete</button>
^^^ This can add up to be a lot of code and messy - here's an OO approach to listeners:Code:$('button.add').click(function(){ //do something }); $('button.update').click(function(){ //do something }); $('button.delete').click(function(){ //do something });
Add data attribute to your buttons:
Now, in your javascipt you want to write less listener code so you check for the data-method value and call that method:HTML Code:<button data-method="add">Add</button> <button data-method="update">Update</button> <button data-method="delete">Delete</button>
There you have it! shortening up the listener code in a jiff!Code://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 } };
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)



Reply With Quote

Bookmarks