greenif
greenif

Reputation: 1093

JavaScript bind event to array of buttons

I try to create array of buttons, bind click event and push variable "editor" to callback function;

  buttons = {
    save:{
      name:  "save",
      title: "save",
      action: function(editor) { alert('Save cliked.'); console.log(editor);}
    },
    preview:{
      name:  "preview",
      title: "preview",
      action: function(editor) { alert("Preview clicked."); console.log(editor);}
    },
    format:{
      name:  "format",
      title: "format",
      action: function(editor) { alert('Format clicked.'); console.log(editor);}
    }
  };


  for (var key in buttons) {
    butHash = buttons[key];
    var button = panel.appendChild(document.createElement("a"));
    button.setAttribute("title", butHash.title);
    button.setAttribute("class", "cm-panel-button " + butHash.name);
    button.textContent = "";
    console.log(button);
    editor = "some editor instance"
    $(button).on('click', function(){
      console.log(butHash.name);
      butHash.action(editor);
    });
  };

When I click to any of this buttons I always see last callback "Format clicked". What I do wrong?

Upvotes: 0

Views: 78

Answers (1)

Javascript closures :) Your code is fine, you just need to move the inside of the for loop into a separate function to create a new scope since in Javascript, closures are created on a function level, not block level.

for(var key in buttons){
  createButton(key);
}

function createButton(key){
  var butHash = buttons[key]
  ...
}

... that should do it.

If you want to read more on closures, I reccomend e.g. this question or possibly this one.

Upvotes: 1

Related Questions