mardi 14 juin 2016

Scope in ES6 and jQuery selectors on click functions


I currently am using jQuery and ES6 to do a simple Read Me toggle. Here is my code and it works on more than one read more on the page.

class ReadMore {
    constructor(cfg) {
        this.toggle = $(cfg.el).find('.read-more-toggle');
        var toggleText = $('.read-more-toggle').text().split(" ")[0];

        $('.read-more-toggle').click(function(e) {
            e.preventDefault();

            if ($(this).hasClass("read-less-toggle")) {
                $(this).parent().prev(".read-more").hide()
                $(this).removeClass("read-less-toggle")
                $(this).text(toggleText + " More");
            } else {
                $(this).parent().prev(".read-more").show();
                $(this).text(toggleText + " Less");
                $(this).addClass("read-less-toggle");
            }
        });
    }
}

export default ReadMore;

I was wondering why is it that when I use this.toggle it only works on one instance of the read-more and not of another instance, but when I use $('.read-more-toggle') directly it works. I think I'm a bit confused by the scope.


Aucun commentaire:

Enregistrer un commentaire