2

I have a Graph class and I want to pass its prototype function to another function. Here is a small snippet code of the class

function Graph(opts) {
    this.filled = opts.filled;
    this.max = opts.max || 50;
    this.min = opts.min || 0;
    this.fixed = 60; //px

    this.transitionArr = [];
    this.timeoutArr = [];
};

Graph.prototype.stopAnimation = function() {
    //stop any css3 transition by removing animation properties
    this.removeAnimProps();
    //stop if there is any timeout
    for (var i = 0; i < this.timeoutArr.length; i++) {
        clearTimeout(this.timeoutArr[i]);
    }

    for (var i = 0; i < this.transitionArr.length; i++) {
        this.transitionArr[i].stop();
    }
};

And what I'm trying to do do is pass stopAnimation function to iterate over all objects to stop all animations in all objects:

function iterateOverAll(userFunc){
    for (var i = 0; i < GraphArr.length; i++) {
        GraphArr[i].userFunc();
    }
}

iterateOverAll(Graph.prototype.stopAnimation);

However, I'm not sure how to do. Any help please?

2 Answers 2

3

If you want to use function as argument, you can pass it like this:

function iterateOverAll(callFunc){
    for (var i = 0; i < GraphArr.length; i++) {
        callFunc.apply(GraphArr[i],[]);
    }
}

iterateOverAll(Graph.prototype.stopAnimation);

This will call your function across all objects, but without any arguments. I think you can modify this function for any arguments.

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

1 Comment

Thanks. I didn't know apply has this functionality.
0

If you already have an array of graphs there is no need to pass the function.

function iterateOverAll(){
    for (var i = 0; i < GraphArr.length; i++) {
        GraphArr[i].stopAnimation();
    }
}

iterateOverAll();

1 Comment

I know, but I do have many functions like stopAnimation. For example, startAnimation, resetAnimation, resetGraph . Therefore, I need to do it in generic way.

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.