0

I have the following code.
How can I execute the the clearSearch method as part of the methods Array?

//Assume this is in a different file, inside a controller. 
//I have access to the controller through a global variable.

function clearSearch() {
    console.log('Search cleared');
}

.

function Task() {
    this.controllers = [];
    this.stores = [];
    this.methods = [];
}

var taskList = [];

var task = new Task();
task.controllers.push('Search');
task.stores.push('search.Case', 'search.Result');
task.methods.push('clearSearch');

taskList.push(task);
3
  • Which clearSearch method? Where is it defined? Commented Feb 19, 2014 at 16:50
  • 2
    You do realize you're pushing strings, right, not methods? Commented Feb 19, 2014 at 16:51
  • I realize I'm pushing Strings, it's why I'm asking this question in the first place. Commented Feb 19, 2014 at 17:05

2 Answers 2

4

If you have the function in your scope:

function clearSearch() { ... }

Then you should reference it by name not by the string and push that:

task.methods.push(clearSearch);

To execute it you can do now:

task.methods[i]();

Where i is the index of the desired function in the array.

Sign up to request clarification or add additional context in comments.

1 Comment

OK, however it is not in the scope, it's under a controller in a different file.
1

You can put the clearSearch function in an object like this:

var obj = {
    clearSearch: function () {
        console.log('Search cleared');
    }
};

Then you can call it like this:

obj['clearSearch']();

Fiddle

See this MDN Article on bracket notation for more information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.