2017-10-31 5 views
0

以内に、私はこのES6クラスを持っている:クラス内ES6コールクラスメソッドだけでなく、クリック機能の

class CommentsController { 
    constructor() { 
    this.$addCommentForm = $('.add-comment') 
    this.$addCommentButton = $('.add-comment input[type=submit]') 
    } 

    init() { 
    this.addCommentFormListener(); 
    } 

    addCommentFormListener() { 
    this.$addCommentButton.on('click', function(e) { 
     e.preventDefault(); 

     let imageId = parseInt($(this).parents('ul').data('id')); 
     let inputText = $(this).parents('ul').find('.user-text').val(); 
     let comment = new Comment(inputText, imageId); 
     debugger; 
     CommentsController.renderComment(comment, imageId) 
    }); 
    } 

    renderComment(comment, imageId) { 
    let image = Image.all[imageId] 
    image.comments.push(comment) 
    $('#images').find(`ul[data-id=${imageId}] ul#comments-${imageId}`).append(`<li>${comment.text}</li>\n`); 
    } 
} 

thisがないため、問題は、デバッガで、私はrenderComment関数を呼び出したいが、私はできないということですコントローラーをもう参照しないでください。私に何ができる?

+0

それは本当に問題ではありませんので、 'renderComment'は、全く' this'を使用していません。 'static'メソッド(インスタンスではなく' CommentController'クラスの上に、それをとにかく呼び出す方法です)を作っても問題ありません。 – Bergi

答えて

1

ではなく、関数のarrow functionを使用します。

矢印関数は、この独自のを持っていません。実行コンテキストを囲む のこの値が使用されます。

thisがインスタンスを参照するためしかし、今は、thisからクリックされた要素を取得することができます。代わりにEvent.targetを使ってクリックした要素を取得:もちろん

addCommentFormListener() { 
    this.$addCommentButton.on('click', (e) => { 
     e.preventDefault(); 

     const $el = $(e.target); 
     const imageId = parseInt($el.parents('ul').data('id')); 
     constinputText = $el.parents('ul').find('.user-text').val(); 
     const comment = new Comment(inputText, imageId); 

     this.renderComment(comment, imageId) 
    }); 
    } 
関連する問題