1

I have one module that I'm using for helper methods, in this module I have a method that will set a keyup eventListener on an element that's passed in. I want to call that helper method from a separate module and pass in a callback using the current modules 'this' context.

//helper module constructor---
function ToolsHelper(options) {
    "use strict";
    this.init(options);
}
//helper module methods---
;(function ($, ba) {
    "use strict";
    ToolsHelper.prototype = {
        constructor: ToolsHelper,
        spaceEnterEvent: function (ele, callback) {
           var spaceKey = 13,
               enterKey = 32;
            if (callback === 0) {
                callback = null;
            }
            ele.addEventListener('keyup', function (e) {
                e = e || window.event;
                var targ = e.target;
                if (e.keyCode === spaceKey || e.keyCode === enterKey) {
                    e.preventDefault();
                    targ.click();
                    if (callback !== null) {
                       callback();
                    }
                }
            });
            return true;
        }
    }

    $(document).on("baCoreReady", function () {
        ba.ToolsHelper = new ToolsHelper();
    });

})(jQuery, ba);

I'm attempting to call this helper from another module [moduleB] using:

ba.ToolsHelper.spaceEnterEvent(trigger, self.updateTabIndexes);
//'self' is set to 'this' in moduleB

Once self.updateTabIndexes() is fired from within moduleB im getting 'cannot read property "settings" of undefined' error - 'settings' is an object defined from within moduleB

MCGRAW
  • 777
  • 14
  • 37

1 Answers1

1

One way to solve this is to bind the context for updateTabIndexes when passing it as a callback:

ba.ToolsHelper.spaceEnterEvent(
  trigger, 
  self.updateTabIndexes.bind(self) // bind the context here
);

Why

In short, the way this gets bound within a function depends entirely on how the function is called, not where its defined.

You may have your function updateTabIndexes defined somewhere in moduleB as a method on an object, but you are passing it into the ToolsHelper as a plain function. Whenever a function is called on its own (i.e. f()), its context is bound to the global object or undefined if in strict mode.

nem035
  • 34,790
  • 6
  • 87
  • 99