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.

http://jsfiddle.net/ebkk8/

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

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -