1

I wanted to set some jQuery animatios dynamically.

The code:

function anim(data) {
    for (index in data) {
        (function(){
            var props = {};
            props[data[index].property] = data[index].value;
            data[index].elem.animate(
                props,
                500,
                function() {
                    data[index].callback();
                }
            );
        })();
    }
}

var data =[
    {
        elem: elem1,
        property: 'prop1',
        value: 'val1',
        callback: function() {
            console.log('callback1');
        }
    },
    {
        elem: elem2,
        property: 'prop2',
        value: 'val2',
        callback: function() {
            console.log('callback2');
        }
    },
];
anim(data);

The problem is binding callbacks. When the callback is fired, data[index] is not available in current scope. Can somebody tell me how to set those callback propery?

2
  • how will you get index in data ? Commented Jan 12, 2017 at 9:39
  • why do you need a closure of IIFE? You can remove it to check or just pass the index there as suggested in the answer below. Commented Jan 12, 2017 at 9:44

2 Answers 2

4

Here you used a closure of Immediately-invoked function expression. You have to pass data[index] as parameter.

(function(dindex){
        var props = {};
        props[dindex.property] = dindex.value;
        dindex.elem.animate(
            props,
            500,
            function() {
                dindex.callback();
            }
        );
 })(data[index]);
Sign up to request clarification or add additional context in comments.

Comments

2

You can try like this as an alternative,

function anim(data) {
    $.each(data, function(x,y){
         var props = {};
         props[y.property] =y.value;
         y.elem.animate(
             props,
             500,
             function() {
                    y.callback();
             }
         );
    });


}

2 Comments

Simply method. +1.
Thank you ! @Alexandru-IonutMihai

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.