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?

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
julew2
  • 199
  • 1
  • 3
  • 13

2 Answers2

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]);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
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();
             }
         );
    });


}
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
Rahul
  • 18,271
  • 7
  • 41
  • 60