问题描述:

I have the following code. Obviously what I want is for the method window.xl.timectrl.Tuio.prototype.tcHour12Changed to get called when this.hour12 gets changed. I'm absolutely sure this.hour12 refers to an actual select box, but nothing happens when I change it. What is wrong here?

window.xl.timectrl.Tuio = function(label_base, update_ui){

this.update_ui = update_ui;

this.hour12 = $('#' + label_base + '_hour12');

this.hour12.off('change').on('change', getSelectBoxHandler(this.hour12, $.proxy(this.tcHour12Changed), this));

}

window.xl.timectrl.Tuio.prototype.tcHour12Changed = function(event, ui, value, id){

//handle event

this.update_ui();

}

function getSelectBoxHandler(select_box, onchange){

var handler = function(event, ui){

var id = select_box.attr('id');

var value = select_box.find('option:selected').attr('value');

onchange(event, ui, value, id);

}

return handler;

}

The point here is for getSelectBoxHandler() to return a handler which is bound to the particular select box and provided handler with a closure. When this returned handler is called when the select box is changed, it will know both the select box to extract the current value from, and the actual onchange handler to pass the value to, in this case, window.xl.timectrl.Tuio.prototype.tcHour12Changed(). i would like this actual handler to have access to members of the object, like this.update_ui(), which is why I wanted the actual handler to be a member of the object instead of a stand-alone function.

This way, this code that extracts the value from the select box does not have to be repeated in every handler, and no explicit call to any function has to be in every such handler to do this work. This approach has worked fine with stand-alone functions, but broke when I tried to use an object member as the handler. I am very interested in why this doesn't work.

网友答案:

I was able to get it working, but not exactly how you have it written. When doing the .on('change',...) part, I couldn't call the getSelectBoxHandler function and pass arguments. If you remove the arguments, for example:

this.hour12.off('change').on('change', getSelectBoxHandler);

Then it started working, but obvously didn't accomplish your goal. So I used an anonymous function instead:

window.xl.timectrl.Tuio = function (label_base, update_ui) {
    this.hour12 = $('#' + label_base + '_hour12');

    this.hour12.off('change').on('change', function () {
        getSelectBoxHandler(this.hour12, $.proxy(this.tcHour12Changed), this);
    });
}

Seems to be working correctly, fiddle here: http://jsfiddle.net/mey9LzLw/

相关阅读:
Top