jquery - Event handlers inside javascript object literal -
i'm trying create object , assign click handlers within it. have realised can't how want due "this" becoming associated button, instead of object literal, breaking access functions.
"uncaught typeerror: object # has no method 'clearselection'"
please see below fiddle.
and here code reference. it's not supposed useful @ stage, except illustrate problem :)
function thingconstructor(somedata) { var button = $("#somebutton"); return { initialise: function () { button.click(function () { // want "this.clearselection();" target // "clearselection" function below. // instead, targets button itself. // how can refer it? this.clearselection(); }); }, clearselection: function () { this.populatelist($("#stuff"), somedata); $("#adiv").empty(); console.log("clearselection"); }, populatelist: function (var1, var2) { //do list } } } $(function () { var test = thingconstructor("somedata"); test.initialise(); });
the this
in click handler domelement , not object.
try this:
initialise: function() { var _this = this; //reference object button.on('click', function () { _this.clearselection(); // use _this }).appendto("body"); },
Comments
Post a Comment