Reputation: 5957
I have a function with an array parameter which contains different values and callbacks.
The aim of this function is to modify one of these callback (the success one's) if it exists in the option array. The modification is to add some actions before executing saved function.
I know that the good word is not "save", but it's hard to explain. So I let you the commented following code which will maybe more clearly.
function myFunction(options){
if (options.success) {
// I would like to save the function without execute it
temporaryVariable = options.success;
}
// Then I want to modify the function into the array parameter in order to add some actions before to execute the previous callback
options.success = function () {
// Some actions
console.log('Some actions');
// Then execute the previous callback I've "save"
temporaryVariable();
};
return options;
}
Any suggestion how to do?
Upvotes: 0
Views: 248
Reputation: 288680
You could use
function myFunction(options){
var temporaryVariable = options.success;
// Then I want to modify the function into the array parameter in order to add some actions before to execute the previous callback
options.success = function () {
// Some actions
console.log('Some actions');
// Then execute the previous callback I've "save"
if (typeof temporaryVariable === 'function') {
temporaryVariable();
}
};
return options;
}
Some notes:
var
.temporaryVariable
, better check typeof temporaryVariable === 'function'
instead of just checking if temporaryVariable
is truly.temporaryVariable
, you don't need to check options.success
when you create temporaryVariable
.Upvotes: 2
Reputation: 13445
It sounds like you just want to create an object, use it as a property bag, then call into the 'current' bag:
function myObject(options)
{
this.options = options;
}
myObject.prototype.changeOption = function(optName, optValue)
{
this.options[optName] = optValue;
}
myObject.prototype.performAction = function()
{
// do something with options;
return this.options;
}
var myObjectInstance = new myObject({'success':true});
myObjectInstance.changeOption('target','someOtherThing');
myObjectInstance.send();
Upvotes: 0
Reputation: 32831
You nearly nailed it:
function myFunction(options){
var temporaryVariable = null;
if (options.success) {
// I would like to save the function without execute it
temporaryVariable = options.success;
}
// Then I want to modify the function into the array parameter in order to add some actions before to execute the previous callback
options.success = function () {
// Some actions
console.log('Some actions');
// Then execute the previous callback I've "save"
if (temporaryVariable) {
temporaryVariable();
}
};
return options;
}
Upvotes: 2