Help with variable scope

I’m trying to use a collection of jquery plugins in my app. I have those loaded fine, but I’m hvaing issues initializing the code to run the object that uses these plugins. Here’s a dirty sample of my object:

var Page = (function() {
    var $foo = $('#fooA'),
            $foob = $('#foob'),
            cc = $('#cthing').plugin(pluginoptions),
            $fooObj = {
                'thing':'otherthing'
            },
            count = 0;
    function init(){
        setJSP( 'init' );
        initEvents();
    }
});

I tried keeping it super super simple at first. One template, static content. The call I need to fire off is Page.init().

I get a tracker error every time, it’s undefined or Page is undefined, or init…I don’t know how else to get this loaded in there. Do I need to load the whole object code, the code for Page within the onRendered call?

Any help is much appreciated.

  1. If you use var Page then that is going to be available only from the current script. Use without var in order to get a variable that is available globally on the client, i.e. Page = (function(...

  2. You have an error in your code. I’m not 100% sure, but you probably want to use this pattern:

Page = (function() {
  return {
    init: function() {
      // do something
    }
})(); // notice the ()

That will actually make Page.init available as a function. But generally try to avoid this pattern as it’s often unnecessarily complex. Just put all the “Page” stuff into client/lib/page.js and use var for anything that you don’t want to leak into global scope and then you don’t need this silly “anonymous function to hide my internal variables” pattern.

  1. Currently $foo and the other vars wouldn’t have any meaningful values. Instead move their initialization to the init() method, that will be called in the onRendered callback. Then those DOM elements will actually exist, I assume. But at page load time they most certainly do not.

HTH!

Thanks! That helped a lot I appreciate the time.

1 Like