Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

Jamie Wilkinson http://tramchase.com

« Newer Snippets
Older Snippets »
3 total  XML / RSS feed 

jQuery namespaced event binding/unbinding

// from a comment by Steven Bristol on errtheblog.com

I just wanted to share a really killer event handling tidbit:

Generally you do something like:

jQuery(’.class’).click(function(){//whatever});


Everyone knows this can be rewritten as:

jQuery(’.class’).bind(‘click’, function(){//whatever});


But sometimes you need to unbind something:

jQuery(’.class’).unbind(‘click’, function(){//});


The problem with this is that it will unbind all the click events, not just yours. So if multiple bits of javascript have a click event handler for ’.class’, unbinding removes them all. (This is because there is no way to identify an anonymous function.)

But jQuery is so good that there is a way to handle this: Namespacing your events:

jQuery(’.class’).bind(‘click.namespace’, function(){//}); 
jQuery(’.class’).unbind(‘click.namespace’);


or for reinitializing an element added via ajax:

jQuery(’.class’)unbind(‘click.namespace’).bind(‘click.namespace’, function(){//});

jQuery and Rails' respond_to

// Just throw this at the bottom of your application.js and you’re good to go: all jQuery ajax requests will trigger the wants.js block of your respond_to declaration, exactly like you’d expect. Enjoy.
// via: http://ozmm.org/posts/jquery_and_respond_to.html

jQuery.ajaxSetup({beforeSend’: function(xhr) {xhr.setRequestHeader(“Accept”,text/javascript”)} })

Javascript Bookmarklets

// various bookmarklets for cloning

javascript:var d=document,f='http://www.facebook.com/share',l=d.location,e=encodeURIComponent,p='.php?src=bm&v=4&i=1190041327&u='+e(l.href)+'&t='+e(d.title);1;try{if(!/^(.*\.)?facebook\.[^.]*$/.test(l.host))throw(0);share_internal_bookmarklet(p)}catch(z){a=function(){if(!window.open(f+'r'+p,'sharer','toolbar=0,status=0,resizable=0,width=626,height=436'))l.href=f+p};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else{a()}}void(0)


javascript:location.href='http://rickrolldb.com/entries/new?url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title);

« Newer Snippets
Older Snippets »
3 total  XML / RSS feed