tags:

views:

361

answers:

3

Hi,

On each page I create my custom js object.

I want to subscribe to the $().ready event so that when it fires, my objects init fucntion also fires.

is this possible?

Updated

My object looks like:

var blah = function() {
    var init = function() {
     //init function stuff
    };
    return {
     InitPage: function() { init(); }
    };
 }();

Then on my page I will do:

blah.init();
+7  A: 
$(document).ready(function() {
    YourObject.init();
});
Luca Matteis
+1 to you and I'll delete my less-specific answer. :-)
Jason Cohen
As a shorthand you could do $(function(){...});
Mark
@Mark — A number of people (myself included) dislike that "shorthand" syntax, as it's less clear what it does just by looking at it.
Ben Blank
updated with my class
not `blah.init()` but `blah.InitPage()`
Luca Matteis
+1  A: 

Check out the jQuery live event.

When you bind a "live" event it will bind to all current and future elements on the page (using event delegation). For example if you bound a live click to all "li" elements on the page then added another li at a later time - that click event would continue to work for the new element (this is not the case with bind which must be re-bound on all new elements).

Example:

$("p").live("click", function(){
    $(this).after("<p>Another paragraph!</p>");
});
Tomas Lycken
+2  A: 

Maybe I am misunderstanding your question but I think what you want to do is put your initialization code inside this block:

$(document).ready(function() {
    // your code here
});

When you pass a function to the jQuery ready() function it aggregates the new function with all previous functions. In other words this will work:

$(document).ready(function() {
    alert("a");
});

$(document).ready(function() {
    alert("b");
});

You don't have to worry about overwriting your previous ready() call.

Andrew Hare
I am creating an object, so from within my object I want to make sure the constructor (or my init method) is called when the DOM is ready.