jquery - OOP JavaScript: Call method from inside of Callback Function -
i'm building jquery app using oop principles , i'm trying implement externally added callback function invokes method inside of object.
function testobject() { var self = this; var functions = new array(); this.updateobject = function() { console.log('updated') } this.addfunction = function(func) { functions.push(func) } this.callfunctions = function() { $.each(functions, function(key, value) { functions[key]() }) } } var myobject = new testobject(); myobject.addfunction( function() { $(':text').on('change', function() { return self.updateobject(); }) } )
this overly simplified version of plugin i'm building. callback works fine, cannot use self.updateobject(); inside of it, since outputs illegal invocation.
how can call method inside callback properly?
the problem self
out of scope of callback function, because function has variables in scope of defined. callback defined outside of testobject
.
a solution bind this
context in callback function self
using function.prototype.call(self)
, when call in callfunctions()
. in callback, can use this
refer testobject
instance. in callback example contains jquery event lose this
context. rectify can create local self
equals this
before jquery change event.
function testobject() { var self = this; var functions = new array(); this.updateobject = function() { console.log('updated') } this.addfunction = function(func) { functions.push(func) } this.callfunctions = function() { $.each(functions, function(key, value) { functions[key].call(self); // call , bind context self }) } } var myobject = new testobject(); myobject.addfunction( function() { var self = this; // needed because change event overwrite 'this' $(':text').on('change', function() { return self.updateobject(); // use self access testobject }) } ) myobject.callfunctions();
alternatively can pass self
argument callback. that, change .call()
line to:
functions[key].call(null, self);
and change callback accept argument so:
myobject.addfunction( function(self) { // self argument $(':text').on('change', function() { return self.updateobject(); // use self refer testobject }) } )
Comments
Post a Comment