javascript - If I create OOP JS code using prototype, how do I reference a class method from a loop? -
i'll show code first:
function messages(){ this.postresponsebutton = '#postresponsebutton'; $(document).ready(this.setevents); } messages.prototype.setevents = function(){ $(self.postresponsebutton).click(function(){ this.postresponse(); // error here }); } messages.prototype.postresponse = function(){ console.log('post response'); } var messages = new messages();
in marked line ("error here"), it's not recognizing messages.postresponse()
function when call this.postresponse()
. i've tried self.postresponse()
without success.
i'm sure it's problem of scope; i'm not sure how refer actual object. need set var me = this
, use that, or something?
thanks time!
as have said, problem context of click
event handler not same function in appears. either bind (es5, won't work in old browsers) function this
:
messages.prototype.setevents = function(){ $(self.postresponsebutton).click(function(){ this.postresponse(); }.bind(this)); }
or save reference this
, use instead:
messages.prototype.setevents = function(){ var = this; $(self.postresponsebutton).click(function(){ that.postresponse(); }); }
a third alternative use $.proxy
, alias function.prototype.bind
including fallback old browsers:
messages.prototype.setevents = function(){ $(self.postresponsebutton).click($.proxy(function(){ this.postresponse(); }, this)); }
Comments
Post a Comment