An interesting problem that I came across today was figuring out how I could elegantly externatize my jQuery functions and bind or unbind them to particular events in a way that would override previous event handling attachments if necessary. The way to go about achieving this is to first define your function as the product of a new variable.
var myAction = function() { alert(‘Lights, Camera, Action!’) ;
Now that this has been defined, the next part of our procedure is attaching the function to an Object’s event so that it can be triggered when a user does something (eg. a click or mouseover event) – in this post, I’ll be using a div called myButton as an example. BelowI have assigned the action myAction to this button. When a user clicks it they will see an alert – simple enough.
Next, a scenario may arise where you would wish to unassign the event you just delegated to myButton – For example: Click was previously told to exectue one specific function but the user-case requires the same button to do something else now that they’ve played around with your page. In order to faciltate this behaviour we first use unbind to remove the first action that was assigned to the button. When you click it it now doesn’t do anything. At this point if I wanted to I could easily define a new function that can be assigned to myButton OR just rebind the old event to the same Object.
//Define a second action
var myAction2 = function() { alert('I'll set Christian Bale on you!')};
//Attach your first action to a click event
$('#myButton').click(myAction);
//Unbind the action from your Objects click event $('#myButton').unbind('click', myAction); //Adjust it back to that it works again
$('#myButton').click(myAction);
// Turn it off once more $('#myButton').unbind('click', myAction); //Assign the second event to it
$('#myButton').click(myAction2);
And thats it. Let me know if it comes in useful ;)
ShareRelated posts:
Related posts brought to you by Yet Another Related Posts Plugin.
No comments yet.
RSS feed for comments on this post. TrackBack URL