Can I put a jquery handler in a constructor?
I'm seeing if I can make some object oriented javascript and I have the following code.
When I went to move my jquery event handler into the constructor I became confused because now I have two this variables...
Am I approaching this incorrectly or is there a way to make it work?
function Dropdown(ddlname) {
this.Value = 0;
this.Selected = false;
this.DDL = ddlname;
this.Limited = false;
this.SelectLast = function () {
$(this.DDL + ' option:last').attr('selected', 'selected');
}
$(ddlname).change(function () {
var v = $(this).val(); // <== ?
if (typeo开发者_运维百科f v == 'number') {
this.Value = v; // <== ?
this.Selected = true; // <== ?
}
});
return true;
};
You need to assign "this" from the context of your constructor to a local variable to be able to reference it from within your jquery event handler.
function Dropdown(ddlname) {
this.Value = 0;
this.Selected = false;
this.DDL = ddlname;
this.Limited = false;
var hold = this;
this.SelectLast = function () {
$(hold.DDL + ' option:last').attr('selected', 'selected');
}
$(ddlname).change(function () {
var v = $(this).val(); // <== ?
if (typeof v == 'number') {
hold.Value = v; // <== ?
hold.Selected = true; // <== ?
}
});
return true;
};
One trick i learnt from Marcelo Ruiz of DataJS team from microsoft is as follows:
function Dropdown(ddlname)
{
var that = this;
//rest of your code. now there is no confusion of this since you have that :)
};
Not sure if this would help you. but just a trick i learned.
Yes you may, but you will need to call the class in the document ready function. I'm pretty sure it's bad practice.
You should consider passing the $ to the constructor or making a jQuery extension.
精彩评论