Is the next function (which actually works) bad in term of best practices?
The IDE is warning me about
'Potentially invalid usage of 'this'. Checks for Javascript 'this' to be in the same closure or outer content.
$(document).on('change', '#select-all', function(){
if( this.checked ) {
$(this).closest('table').find('input[name="row-id"]').each( function() {
this.checked = true; // Here
})
}
else {
$(this).closest('table').find('input[name="row-id"]').each( function() {
this.checked = false; // Here
});
}
});
When I check a checkbox with ID select-all
, it marks all the other as selected.
Most probably it happens because your IDE doesn't know what object this
refers to in the functions you use, hence giving you a hint that this
might refer to window
object or another context.
By the way, your code can be rewritten to:
$(document).on("change", "#select-all", function() {
$(this)
.closest("table")
.find("input[name='row-id']")
.prop("checked", this.checked);
});
@Jorge it has to do with the scope of closures in javascript and the usage of this
.
For further reading try this one: http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
I haven't read it completely but it sums it pretty nicely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With