Search code examples
javascripthtmlwysihtml5

Create wysihtml5 dynamically


Hi i´m trying to create multiple textareas with wysihtml5 0.3.0. First generate HTML an then initialize the editors, I must customize blur for each textarea.

    <div id="toolbar0" style="display: none;">
        <a data-wysihtml5-command="bold" title="CTRL+B">bold</a> |
        <a data-wysihtml5-command="italic" title="CTRL+I">italic</a>
        <a data-wysihtml5-action="change_view">switch to html view</a>
      </div>
      <textarea id="textarea0" placeholder="Enter text ..."></textarea>
      <br>
       <br>
      <div id="toolbar1" style="display: none;">
        <a data-wysihtml5-command="bold" title="CTRL+B">bold</a> |
        <a data-wysihtml5-command="italic" title="CTRL+I">italic</a>
        <a data-wysihtml5-action="change_view">switch to html view</a>
      </div>
      <textarea id="textarea1" placeholder="Enter text ..."></textarea>
      <br>
      <br>
      <div id="toolbar2" style="display: none;">
        <a data-wysihtml5-command="bold" title="CTRL+B">bold</a> |
        <a data-wysihtml5-command="italic" title="CTRL+I">italic</a>
        <a data-wysihtml5-action="change_view">switch to html view</a>
      </div>
      <textarea id="textarea2" placeholder="Enter text ..."></textarea>
<script>
    var editor = [];
    var aux = [];

      for(var i = 0; i <= 2; i++)
        {
            editor[i] = new wysihtml5.Editor("textarea" + i, {
                toolbar:      "toolbar" + i,
                parserRules:  wysihtml5ParserRules
            });

              aux[i] = editor[i].getValue();
              var log = document.getElementById("log");

              editor[i]         
                .on("blur", function() {
                  log.innerHTML += "<div>blur"+i+"</div><div>"+ aux[i] +"</div>";
                })
        }
</script>

Always in the blur event get the last textarea and undefined value: blur3 undefined,blur3 undefined,blur3 undefined

Could someone help me out, thanks in advance.


Solution

  • You are into a function closure problem. When you define each onblur event, you tell Javascript to read the same i value for all of them (and in the end it becomes i=3).

    Change it into this:

    editor[i].on("blur", function(index) {
        return function() { log.innerHTML += "<div>blur"+index+"</div><div>"+ aux[index] +"</div>"};
    }(i));