Q: A method adding an event calling an other method I need to create an object that have at least two methods. The first method creates an event that bind a button to the second method of the object. 
But, I have a problem at the creation of the event. The this keeps being attached to the button and not the instance of the object. 
I tried bind() but if it is the solution I didn't find the good way to use it.
Is it even possible to do that? And, if yes, how can it be done?


function obj()
{
  this.attribute = 42;
  this.eventer();
}

obj.prototype.eventer = function()
{
  $("#but").on("click",this.print);
}

obj.prototype.print = function()
{
  $("#print").html(this.attribute);
}

var test = new obj();
<script src='//code.jquery.com/jquery.min.js'></script> 
<button id="but">Click me !</button>
<div id="print"></div>    



A: From the javascript reference manual for bind():

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Simply use this.print.bind(this), when passing the handler to the click event.


function obj()
{
  this.attribute = 42;
  this.eventer();
}

obj.prototype.eventer = function()
{
  $("#but").on("click",this.print.bind(this));
}

obj.prototype.print = function()
{
  $("#print").html(this.attribute);
}

var test = new obj();
<script src='//code.jquery.com/jquery.min.js'></script> 
<button id="but">Click me !</button>
<div id="print"></div>


