How to pass a specific array element for an event callback

I have an array of objects that contains every id, selector and actionButton callback

var actionButtons = [
    {
        id:"0",
        selector:"._55ln._qhr",
        callback: undefined
    },
    {
        id:"1",
        selector:"._22aq._jhr",
        callback: undefined
    },
    .
    .
    .
];

What I'm trying to do is call a function with a specific parameter from an array (id) each time the selector is pressed.

for(var i=0;i<actionButtons.length;i++){
    $(document).on('click', actionButtons[i].selector, function() {
        makeAction(actionButtons[i].id);
        if (actionButtons[i].callback)
            actionButtons[i].callback(this);
    });
}

But this code does not work; it looks like every time a callback function is called a value iequal to the size of the array.

How can I solve this problem i.e. so that the value of the variable ibecomes different for each callback.

+6
source share
3 answers

, i. , , , i - , 0.

, :

for(var i = 0; i < actionButtons.length; i++) {
  (function(i) {
    $(document).on('click', actionButtons[i].selector, function() {
      makeAction(actionButtons[i].id);
      if (actionButtons[i].callback)
        actionButtons[i].callback(this);
    });
  })(i);
}
+5

, ,

actionButtons.forEach(function(ab) {
  $(document).on('click', ab.selector, function() {
    makeAction(ab.id);
    ab.callback && ab.callback(this);
  });
});
+2

You can use let :

The let statement declares a local variable for the block region, optionally initializing it with a value.

Let assures you of closure.

for(let i=0;i<actionButtons.length;i++){
   $(document).on('click', actionButtons[i].selector, function() {
       makeAction(actionButtons[i].id);
       if (actionButtons[i].callback)
         actionButtons[i].callback(this);
     });
}
0
source

All Articles