Julian Julian - 2 months ago 14
jQuery Question

jQuery: anonymous function onclick and onready

First of all, the code is working, but in my opinion not ideal.

I like anonymous functions in Javascript. So I can use an anonymous function when registering an

onclick
handler:

$(function()){
$(".foo").on("click", function() {
..
});
}


But sometimes, I realize that I need to call the function also
onReady
. So, I can convert the code to:

$(function()){

function bar() { .. }

$(".foo").on("click", bar);

bar(); //'onload'
}


But thats a lot of work! (laziness is a good characteristic of a programmer). I have to create a non-anonymous function, change the onclick registrion etc. Is it possible to keep the anonymous function?

In the ideal situation, I have something like:

$(function()){
$(".foo").on("click onDomLoaded", function() {
..
});
}


but thats not working.

(only option I see is to extend the 'on' function, but that seems ugly)

Answer

The idea of @tymejV was close, but I could have some undesired side effects - for example, already bounded click events. fortunately we have 'namespaced events' in jQuery which solves the problem:

$(function()){
  $(".foo").on("click load.somenamespace", function() {
     ..
  }).trigger("load.somenamespace");
}
Comments