简体   繁体   中英

function call is not defined inside template literal

Hi I have a function like this, I'm trying to build a markdown editor

var Editor,
  __bind = function(fn, h) {
    return function() {
      return fn.apply(h, arguments);
    };
  };

Editor = (function() {
  function Editor(selector, options) {
    this.variable = __bind(this.varirable, this);
  }

Editor.prototype.variable = function(name) {
    this.editor.doc.replaceSelection('#' + name + '#');
    return this.editor.focus();
};

Editor.prototype._buildToolbar = function() {
    var $md = this;

$(`<div class="dropdown" style="display:inline">
  <a class="btn dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
  style="padding:0 0 0 10px;color: #000;box-shadow: none;height:100%;line-height:26px;">v</a>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuLink" style="box-shadow: 0 0px 5px 0 rgba(0,0,0,.25);border-radius: 0;margin-top: -1px;">
    ${Object.keys(this.options.vars)
      .map(function(key) {
        return (
          '<a class="dropdown-item" id="' +
          $md.options.vars[key].VariableName +
          '" href="#" onClick="variable(' +
          $md.options.vars[key].VariableName +
          ')">' +
          $md.options.vars[key].VariableName +
          '</a>'
        );
      })
      .join('')}
  </div></div>`).appendTo(this.toolbar);
};

The problem is that when I click on the link I got Uncaught ReferenceError: variable is not defined I've even tried to call it using $md.variable(name) but same thing.

There is no need to modify Editor s prototype and it won't work the way you call the method.

Just change

Editor.prototype.variable = function(name) {
  this.editor.doc.replaceSelection('#' + name + '#');
  return this.editor.focus();
};

to

function variable(name) {
  this.editor.doc.replaceSelection('#' + name + '#');
  return this.editor.focus();
};

and your click handler should work.

greetings

note : this will point to what called variable() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM