Using ".call" in JavaScript
Every so often I find myself binding a function to an event, but I want to also run that function on page load. Sometimes you can just invoke the event right away, like this:
[js]
$(".some_element").change(function() {
//do something
}).change();
[/js]
That can have side effects that you don't want though, such as executing other functions unintentionally. In that case, you can name the function and call it explicitly after the bind, like this:
[js]
function doSomething() {
//do something
}
$(".some_element").change(doSomething);
doSomething();
[/js]
That has another problem though. If you were using "this" and expecting it to be the changed element (which you probably were), then that context won't be set. Luckily, there is an easy way to get around that as well. You can invoke the function in a different way and set the context to be a specific DOM element, just like jQuery itself does.
[js]
$(".some_element").change(doSomething).each(function() {
doSomething.call(this);
});
[/js]
This way, you can write the function assuming the context of this like you normally would and still directly invoke it as need be.