Search code examples
javascriptjquerythisjquery-callback

How to pass object context to .on() callback function


I'm working on structuring my JavaScript by using the Module Pattern as explained here.

This is a very simplified version of my code:

var obj = {
  bindUIActions: function(){
    $('#button').on('click', {self: this}, this.doStuff);
  },
  doStuff: function(e){
    $(this).fadeOut();
    var self = e.data.self;
    self.doSomethingElse();
  },
  doSomethingElse: function(){
    //....
  }
}

I need to pass the object context to the doStuff method because I don't want to use:

obj.doSomethingElse();

So I can use the code again somewhere else, or change the object name ('obj') later on. Using event data does not feel as the best solution, so is there a better way to get this done?

I've used $.proxy to change the context for the .on() callback function and that works. The problem is that I need to keep the this context from the click-element also, to get

$(this).fadeOut();

to work.

Thanks in advance!


Solution

  • I think you could set the context with one of these: