Skip to content

Instantly share code, notes, and snippets.

@lastobelus
Created November 24, 2012 20:13
Show Gist options
  • Save lastobelus/4141241 to your computer and use it in GitHub Desktop.
Save lastobelus/4141241 to your computer and use it in GitHub Desktop.
// JQuery Best Practices
/************* Scope *********************/
// write methods that add handlers etc. so that they can be re-used in scopes other than document.ready
// http://www.braindonor.net/blog/jquery-best-practices-part-1-managing-scope/406/
function my_button(scope) {
scope.find('.button').click(function(){
alert("You Clicked The Button");
})
}
$(document).ready(function(){
my_button($(this));
});
$.ajax({
type: 'POST',
url: 'http://mysite.com/ajaxurl',
success: function(data) {
$('.data-target').html(data);
my_button($('.data-target'));
}
});
/* NOTE: don't do
$(document).ready(function () {
my_button_jquery(document);
})
because going through the jquery object is expensive
*/
/************* Chaining *********************/
/*
place a chained function on a new, indented line when one of the following conditions have been met:
1. The function being chained has a function embedded as one of the arguments.
2. The function being chained would create a line that would wrap in editor.
3. Another function in the chain is on a new, indented line.
example:
*/
scope.find('.button')
.click(function(){
alert("You Clicked The Button!");
});
// avoid using multiple calls to get jquery sets by using chaining:
scope.find('div.vehicle-button a')
.hover(
function () {
$(this).parent()
.addClass('vehicle-button-hover')
.find('div.button')
.addClass('button-hover');
},
function () {
$(this).parent()
.removeClass('vehicle-button-hover')
.find('div.button')
.removeClass('button-hover');
}
)
.mousedown(function () {
$(this).parent()
.find('div.button')
.addClass('button-click');
})
.mouseup(function () {
$(this).parent()
.find('div.button')
.removeClass('button-click');
});
/************* Plugins *********************/
// Standard Plugin Shell
(function($) {
// Shell for your plugin code
$.fn.nameOfPlugin = function(options) {
options = $.extend({}, $.fn.nameOfPlugin.defaults, options);
return this.each(function() {
// Do something to each item
});
};
$.fn.nameOfPlugin.defaults = {
color : '#fff47f',
duration : 'fast'
};
})(jQuery);
// $.fn is an alias of the jQuery.prototype
// now this can be called as $(some-query).nameOfPlugin()
// and it will return the $(some-query) set so it can be used in chains
// http://www.websanova.com/tutorials/jquery/10-coding-tips-to-write-superior-jquery-plugins#.ULElnaXA8YI
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment