Event handlers inside javascript literal object

I am trying to create an object and assign click handlers from it. I realized that I could not do this, because "this" becomes associated with the button, and not with the object literal, violating access to functions.

"Uncaught TypeError: Object # does not have a 'clearSelection' method"

See below script.

http://jsfiddle.net/ebKk8/

And here is the code for reference. At this point, he should not do anything useful except to 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(); }); 
+4
source share
1 answer

this in your click handler contains DOMElement and not your object.

Try the following:

 initialise: function() { var _this = this; //reference to this object button.on('click', function () { _this.clearSelection(); // use _this }).appendTo("body"); }, 
+9
source

Source: https://habr.com/ru/post/1498640/


All Articles