0

I'm enjoying RequireJS and finally having some modularity/encapsulation in Javascript but I've hit a snag when passing callbacks to another module.

Specifically, I have created a menu module for my application. It can be loaded by another module, from which you can add menus using an exposed function in said menu module.

Now, this menu items can have handlers, e.g. form submission or on click for example. Furthermore, the callback will typically access functions defined privately/internally in the calling modules, that is, the one making use of the menu function.

I've tried:

  • binding the event to the element before passing it to the menu function but this didn't work.
  • passing the callback function as a second parameter and binding it in the menu module

Neither of these worked.

Any ideas?

Some code for more detail

Menu module function

function addMenuItem(jqObj, evtHandler) {
    console.log("Adding menu " + jqObj);
    jqObj.click(evtHandler);
    menuList.append($("<li>").append(jqObj));
}



Calling function in menu using module

function addSelectionMenuItem() {
    satInput = $("<input type=search placeholder='search' />");
    menuModule.addMenuItem(satInput, function() {
        this.loadCzml(satInput.val());
        console.log("Checking execution...");
    });
}

Thanks!

3 Answers 3

0

I doubt that this is the value you need in your event handler. Change your call to addMenuItem so that it reads:

var self = this;
menuModule.addMenuItem(satInput, function() {
    self.loadCzml(satInput.val());
    console.log("Checking execution...");
});

I've added an assignment to self before the call and use self instead of this in the callback. jQuery documentation on the value of this:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector.

0

Change the context of the event handler with .bind()

jqObj.click(evtHandler.bind(this);
0

Ok, it was not a modular scope problem with the callback afterall.

A plugin used in the menu module was cloning the html elements using the jquery clone method. However, it was not passing an argument to the clone method so it defaulted to not cloning any handlers.

This meant the input passed by the calling module was no longer what was visible on the page, the cloned version was with no handlers!

At least the plugin was open source so I could see the code.

Thanks anyway :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.