O
O
OneTwoThreeFourFive2021-09-20 11:25:53
JavaScript
OneTwoThreeFourFive, 2021-09-20 11:25:53

Am I using jquery and oop correctly?

Instead of this

$('.test').click( function() {
  $(this).remove();
});


write it
class Test {
    constructor(item) {
      this.wrapper = $(item);

      this.setClickEvent();
    }

    setClickEvent(item) {
      this.wrapper.click( () => {
        // do some things

        this.remove();
      });
    }

    remove() {
      // do some things
      this.wrapper.remove();
    }
  }

  new Test('.test');


This is a simple example, but sometimes you need many different actions for an element or for nested elements. Normal or not?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-09-20
@delphinpro

KISS

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question