简体   繁体   中英

How to define events within a class in ECMA 6 using jquery selectors?

I've defined a class with the new standard ECMA6 and I want to put all the click events and other stuff within the class. How can I do that? I've search across several articles and none of them mention how to do this......I tried to define the events on the constructor like this but didn't work at all:

   class Grid{

        constructor(gridOptions) {
         this.grid_header='';
         this.grid_body='';
         this.grid='';   
         this.options=gridOptions;
         this.cacheDom();
         this.bindEvents();
         this.buildGrid();

       $( ".page" ).on( "click", function() {
               alert("hola");
             });


        }

        cacheDom() {
           this.$greeder = $(this.options.selector);
        } 

        bindEvents() {

        }

        buildGrid(page_number=1){


        }


    }

EDIT: I want that everytime that event gets triggered, to execute a method from my class

ES6 doesn't change the way jQuery and DOM events and event handlers work.

What you have currently should 'work', ie it should add a click handler for all the elements that have .page class name and exist in the DOM at the time that specific code is executed. If the elements are generated dynamically after the event binding then your code won't work as the target elements do no exist in the DOM yet. You should use event delegation.

$('aStaticParentSelector').on('event', '.selector', handler);

See Understanding Event Delegation .

And if you have a class and there are elements that are generated by the class then you should think about a different approach for selecting the class-related elements.

class Foo {
   constructor() {
      this.$el = jQuery('<div class="page">').appendTo('.somewhere');
      this.$el.on('click', this.clickHandler.bind(this));
   }

   clickHandler(event) {
    // `this` keyword refers to the instance
    // `this.$el` => a jQuery wrapped element
    // `event.currentTarget` => the DOM element that is wrapped by jQuery in `this.$el`
   }
}

The above code uses Function.prototype.bind for setting the this value of the handler.

Please note that ES6 classes are just syntactic sugar and doesn't fundamentally change the way JavaScript OOP system work.

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