无法触发事件"Uncaught ReferenceError: killMedia is not defined"



我正在用Riot.js制作网页杂志的WYSIWYG编辑器。当我点击添加按钮时,我想显示带有删除图标的instagram图像,当我点击删除图标时,我想删除instagram图像

我可以显示带有删除图标的instagram图像,但不能删除它们,因为函数killMedia不起作用。当我点击删除图标时,我得到这个错误消息。

Uncaught ReferenceError: killMedia is not defined

我在下面的代码工作。有人知道是什么问题吗?

<div id='body-text' class='body-text' contenteditable=true data-placeholder='Body Contents'></div>
<label>
    <input type='text' name='instagram' placeholder='Input Instagram embed code'>
    <button onclick={ addInstagram }>add</button>
</label>

<script>
addInstagram(e) {
    var embedCode = this.instagram.value
    var instagram = document.createElement('div')
    instagram.setAttribute('class', 'media-frame')
    instagram.setAttribute('show', '{showMedia}')
    instagram.innerHTML = embedCode
    var i = document.createElement('i')
    i.setAttribute('id', 'media-killer')
    i.setAttribute('class', 'fa fa-times-circle-o media-killer')
    i.setAttribute('aria-hidden', 'true')
    i.setAttribute('show', '{showMedia}')
    i.setAttribute('onclick', '{killMedia}')
    var target = document.getElementById('body-text')
    instagram.appendChild(i)
    target.appendChild(instagram)
    this.instagram.value = ''
    this.update()
    this.modal = false
}
this.showMedia = true
killMedia(e) {
    this.showMedia = false
    this.update()
}
</script>

用于定义函数killMedia的语法不正确。Riot.js似乎有一些事件处理程序的替代语法,这就是为什么它适用于addInstagram

在JavaScript中有几种正确声明和定义函数的方法。一个是:
// declare variable killMedia and assign a function to it
var killMedia = function( e ){
    this.showMedia = false;
    this.update();
}

另外,我对Riot.js将如何调用事件函数一无所知,所以,由于您在killMedia函数中使用this,您可能需要在声明它时将适当的this绑定到函数。一种方法是使用bind函数:

// declare variable killMedia and assign a function to it
var killMedia = function( e ){
    this.showMedia = false;
    this.update();
}.bind( this );

如果语法不是问题,并且Riot.js正在处理killMedia的特殊声明,您可能只需要在 addInstagram之前声明killMedia ,即将该函数移到addInstagram之上。这只是一个猜测,因为我对Riot.js一无所知。

我添加了这个作为评论,但现在我有时间实现它。我认为这是不工作的,因为你试图动态加载元素,所以不是由Riot编译器编译。

一种更像Riot.js的方法是构建另一个可以删除的名为instagram_image的标签,并有一个数组来迭代父标签中的图像。

我简化了你的代码,但想法是这样的:(这里是柱塞版本http://plnkr.co/edit/EmkFhq0OyVtwSNIJqeJF?p=preview)

<my-tag>
  <span each={img in instagram_images} >
    <instagram_image embed_code={img.embed_code}></instagram_image>
  </span>
  <label>
      <input type='text' name='instagram' placeholder='Input Instagram embed code'>
      <button onclick={ addInstagram }>add</button>
  </label>
  <script>
    this.instagram_images = []
    addInstagram(e) {
        var instagram_image = {embed_code: this.instagram.value}
        this.instagram_images.push(instagram_image)
        this.instagram.value = ''
    }
  </script>
</my-tag>
<instagram_image>
  <div onclick={remove}>
      {opts.embed_code}
  </div>
 <script>
   this.remove = function() {
    this.unmount()
    this.update()
   }
 </script>
</instagram_image>

相关内容

最新更新