Skip to content

Instantly share code, notes, and snippets.

@ariellephan
Last active September 13, 2016 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ariellephan/ecd42fd32e50a610b4da2db1c9d615ef to your computer and use it in GitHub Desktop.
Save ariellephan/ecd42fd32e50a610b4da2db1c9d615ef to your computer and use it in GitHub Desktop.
jQuery best practice. patterns/anti patterns
//bad
$("#agree").bind("change", function() {
if ($("input[type=submit]").hasClass("disabled")) {
$("input[type=submit]").removeClass("disabled");
} else {
$("input[type=submit]").addClass("disabled");
}
});
//good
$("#agree").bind("change", function() {
var $input = $("input[type=submit]"),
isDisabled = $input.hasClass("disabled");
$input.toggleClass("disabled", isDisabled);
});
//ok
function doSomething(el){console.log(el)};
$.each([3,4],doSomething);
//better if >= ie9
function doSomething(el){console.log(el)};
[3,4].forEach(doSomething);
-> only $.each if loop through jquery list of objects.
//nope
$("li").forEach(func)
//yes
$("li").each(func)
//what if its an array of object and you want to access value of each object certain prop
$.each([{x:3},{x:4}],doSomething); // 0, 1
[{x:3},{x:4}].forEach(doSomething);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment