I'm trying to create an object and assign click handlers from within it. I have realised I can't do it how I want due to "this" becoming associated with the button, instead of the object literal, breaking access to the functions.
"Uncaught TypeError: Object # has no method 'clearSelection'"
Please see the below fiddle.
http://jsfiddle.net/ebKk8/
And here is the code for reference. It's not supposed to do anything useful at this stage, except illustrate the problem :)
function ThingConstructor(someData) {
var button = $("#someButton");
return {
initialise: function () {
button.click(function () {
// I want "this.clearSelection();" to target the
// "clearSelection" function below.
// Instead, it targets the button itself.
// How can i refer to it?
this.clearSelection();
});
},
clearSelection: function () {
this.populateList($("#stuff"), someData);
$("#adiv").empty();
console.log("clearSelection");
},
populateList: function (var1, var2) {
//do something to a list
}
}
}
$(function () {
var test = ThingConstructor("someData");
test.initialise();
});
The this
in your click handler is the DOMElement and not your object.
Try this:
initialise: function() {
var _this = this; //reference to this object
button.on('click', function () {
_this.clearSelection(); // use _this
}).appendTo("body");
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With