简体   繁体   English

为什么我的听众没有依附?

[英]Why isn't my listener attaching?

I originally had the code in addCommentFormListener in the init method and it worked. 我最初在init方法的addCommentFormListener中包含代码,并且可以正常工作。 I am trying instead to attach the listener to the relevant elements like so: 我正在尝试将侦听器附加到相关元素,例如:

class CommentsController {
  constructor() {
    this.$addCommentForm = $('.add-comment')
  }

  init() {
    $(".add-comment").each(function() {
        console.log('test2')
        this.addEventListener("submit", this.addCommentFormListener);
    })
  }

  addCommentFormListener() {
        e.preventDefault();
        console.log('test');
        var image = $(this).closest(".image");
        var imageId = image.find("ul").attr("id");
        var commentContents = $(this).find('input[name="comment-description"]').val();
        console.log(commentContents);
        // var imageObject = Image.all.find(image => image.id => imageId);
    }
}

The console logs test2 the appropriate amount of times, but nothing else happens when I click submit on a given element. 控制台会记录test2适当的时间,但是当我在给定元素上单击“提交”时,什么也不会发生。 What am I missing? 我想念什么?

Separately, it feels strange to me to have the event listener attached on submit , rather than for it to already be there and just activated when I hit submit, but that may be just my weak understanding of Javascript listeners. 另外,感觉奇怪,我有事件监听器安装在submit ,而不是它已经在那里了,只是被激活,当我点击提交,但是这可能只是我的javascript听众的薄弱理解。

Edited to add HTML: 编辑添加HTML:

<form id="add-comment" class="add-comment" data-id="0" action="#" method="post">
        <label for="comment-description">Comment: </label>
        <input type="text" id="comment-description-0" class="user-text" name="comment-description" placeholder="comment">
        <input type="submit" value="(+) add comment">
      </form>

Within the callback passed to each() , this isn't what you think it is. 在传递给each()的回调中, this不是您认为的那样。 It is the current element within the iteration, which is why this.addEventListener works, but of course then it can't be the CommentsController instance at the same time, so the actual callback you're passing is undefined . 这是迭代中的当前元素,这就是this.addEventListener起作用的原因,但是当然不能同时作为CommentsController实例,因此您传递的实际回调是undefined

Since you're using ES6, the easiest way is to use an arrow function: 由于您使用的是ES6,最简单的方法是使用箭头功能:

  init() {
    $(".add-comment").each((index, element) => {
        console.log('test2')
        element.addEventListener("submit", this.addCommentFormListener);
    })
  }

Also note that within addCommentFormListener , this will refer to the element that the event was fired on, not to your CommentsController instance. 还要注意,在addCommentFormListenerthis将指向触发事件的元素,而不是 CommentsController实例。 This works alright currently, but might be confusing if you revisit this code in a month :) 这目前可以正常使用,但是如果您在一个月后重新访问此代码,可能会造成混淆:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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