I’m implementing a client-side ‘custom control’ but I’m struggling to get a reference to the the object that created the control in my event handlers. Its best explained with some boiled down code;
function myControl(text) {
this.Text = text;
this.DoAlert = function (e) { alert(e.Text); };
this.Create = function (container) {
var btn = $('<BUTTON/>');
btn.html('Click Me');
container.append(btn);
btn.bind('click', this, this.DoAlert);
}
}
$(document).ready(function () {
var control1 = new myControl('Button 1');
control1.Create($('#container'));
var control1 = new myControl('Button 2');
control1.Create($('#container'));
});
As you can see, I’m creating two instances of myControl initialised with different strings, inside DoAlert, how do I get the reference the object that created the button, so that I can get to its properties?
Is this an acceptable approach for Javascript/ jQuery or should I be doing something else?
You have various options:
1) You could include
thisinside the closure around the event handler:The variable _this will be bound to
thiseven inside the functionDoAlert.2) You use
$.proxy(ref http://api.jquery.com/jQuery.proxy/):3) Use the event data properly (ref: http://api.jquery.com/bind/)
I would personally recommend 2) because it is very transparent (
thisin the constructor is the same asthisin the event handler).