I am struggling to figure out how to make this function pass by reference in my code. Is there a way to achieve this?
var Class = function() {
var callback1;
var callback2;
function buildStuff(data, callback) {
element.onclick = function() {
doStuff(callback);
};
}
function doStuff(callback) {
callback();
}
return {
"setCallback1":function(fn) {
callback1 = fn;
},
"setCallback2":function(fn) {
callback2 = fn;
},
//may rebuild with different data, but same callback
"buildFoo":function(data) {
buildStuff(data, callback1);
},
//may rebuild with different data, but same callback
"buildBar":function(data) {
buildStuff(data, callback2);
}
};
}
function main() {
var object = Class();
object.setCallback1(function() {
//do stuff
});
object.setCallback2(function() {
//do something else
});
}
After clicking on the element, the callback
variable is returning as undefined
. I was expecting it to be the anonymous function set using the setCallback
function, but it seems the user click occurs before the setCallback
function is called.
Thank you for any help!
UPDATE: I realize now that I need to dynamically set what callback
equals. So simply removing the callback
parameter from buildStuff
won't work in my situation.
UPDATE2: Apologies for the confusion earlier. The buildStuff
function is actually a private member function within the class (utilizing the module pattern) and is called multiple times. Depending on the object being built, it requires a different callback. The callback is set externally to the class, hence the need for dynamic assignment. I've made some adjustments to my code to clarify this. Sorry for any misunderstandings.