Last active
September 13, 2016 00:07
-
-
Save ariellephan/ecd42fd32e50a610b4da2db1c9d615ef to your computer and use it in GitHub Desktop.
jQuery best practice. patterns/anti patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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