Question

I have created a Javascript namespace to avoid conflict with other Javascript codes.

var ns = {
   init: function() {
      $('a').click(this.clickHandler);
   },
   clickHandler: function() {
      // Some code here ..

      // The keyword "this" does not reference my "ns" object anymore. 
      // Now, it represents the "anchor"
      this.updateUI();
   },
   updateUI: function() {
      // Some code here ...
   }
};

Please, how can I reference my enclosing namespace?

Was it helpful?

Solution

$.proxy

$('a').click($.proxy(this.clickHandler, this));

OTHER TIPS

You can bind event handler to an anonymous function and call clickHandler within it. This way the context will still refer to ns object.

var ns = {
   init: function() {
      var self = this; // store context in closure chain
      $('a').click(function () {
         self.clickHandler();
      });
   },
   clickHandler: function() {
      this.updateUI();
   },
   updateUI: function() {
      // Some code here ...
   }
};

Here is an article: http://www.codeproject.com/Articles/108786/Encapsulation-in-JavaScript

It explains to create a closure in the namespace where you can store stuff (like the original 'this')

var ns = (function () {
    var self;

    return {
        init: function () {
            self = this;
            $('a').click(this.clickHandler);
        },
        clickHandler: function () {
            // Some code here ..
            self.updateUI();
        },
        updateUI: function () {
            // Some code here ...
        }
    };
})();

FIDDLE HERE

A good way to do that is to define a local variable in a function that refers to it. This helps when "this" changes on you. Your code could look something like this:

var ns = new (function() {
    var self = this;
    self.init = function() {
        $('a').click(self.clickHandler);
    },
    self.clickHandler = function() {
        // Some code here ..

        // The keyword "this" does not reference my "ns" object anymore. 
        // Now, it represents the "anchor"
        self.updateUI();
   },
   self.updateUI = function() {
      // Some code here ...
   }
})();

This allows you to still reference the event handler with this and then reference your namespace with the locally defined reference that is only available from within.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top