0

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?

1 Answer 1

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.

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

2 Comments

Thanks a lot, you save second half of my day. :-)
You are very welcome :) If you have the time, check out the links attached since it is definitely worth making sure that you understand how closures in Javascript work.

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.