2

Considering the following code:

var SomeObject = function (id) {
    this.id = id;    
};
SomeObject.prototype.Handler = function() { alert(this.id);};

var o = new SomeObject("bla");

$('#someDivId').on('shown.bs.modal', o.Handler);

I was expecting a popup saying "bla", but I get a popup saying "someDivId".

Is there a way to use an instance method as an event handler ?

I read Class methods as event handlers in JavaScript? and Using an object's method as an event handler, how do I remove it? but I can't transcript them to my case.

tschmit007
  • 7,559
  • 2
  • 35
  • 43
  • This is likely due to the fact that when you're specifying your event handler, the `this` context is not being propagated. – Matthew Sep 05 '18 at 16:03

4 Answers4

5

The context of this depends on who invoke the function.In this case it is invoked by the dom element.

If you console.log(this) inside the Handler it will log the dom & that dom has an id attribute, so you are seeing someDivId as the output

You need to bind o if you want to change the context

var SomeObject = function(id) {
  this.id = id;
};
SomeObject.prototype.Handler = function() {
  alert(this.id);
};

var o = new SomeObject("bla");

$('#someDivId').on('click', o.Handler.bind(o));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someDivId">hello</div>;

Note:Here the bootstrap event shown.bs.modal is replaced by 'click` for this demo

brk
  • 48,835
  • 10
  • 56
  • 78
2

You're not assigning "o" a type. Surely it should be:

var o = new SomeObject("bla");

Instead of

var o = new ("bla");
sparkhead95
  • 395
  • 4
  • 14
0

You will need $('#someDivId').on('shown.bs.modal', o.Handler.bind(o));

Herman Starikov
  • 2,636
  • 15
  • 26
0
$('#someDivId').on('shown.bs.modal', o.Handler);

The 'this' is $('#someDivId') in this case because the object calling is the element.

$('#someDivId').on('shown.bs.modal', function() { o.Handler() });

Place the call inside an anonymous function and actually call it and the 'this' will be the object 'o'.