简体   繁体   中英

Why isn't my listener attaching?

I originally had the code in addCommentFormListener in the init method and it worked. 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. 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.

Edited to add 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. 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 .

Since you're using ES6, the easiest way is to use an arrow function:

  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. This works alright currently, but might be confusing if you revisit this code in a month :)

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