javascriptecmascript-5es5-shim

Modular JS: How to pass variables and event


I have this JS code:

        const getData = {

            // set vars
            start_date: <?php echo $start_ts; ?>,
            end_date:   <?php echo $stop_ts; ?>,

            init: function() {
                this.cacheDom();
                this.bindEvents();
            }, 
            cacheDom: function() {
                this.form = form;
                this.show = show;               
            }, 
            bindEvents: function() {
                this.show.click(this.sendData(this.start_date, this.end_date));
            },
            sendData: function(sdate, edate, e){
                e.preventDefault();
                // this.form.submit();
                console.log(sdate);
                console.log(edate);
            },
            render: function() {}


        }
        // run object
        getData.init();

I'm trying to pass this.start_date and this.end_date with the click event. Tried in a few different ways (the one you see is one of them)

Please help me pass the click event with the variables.


Solution

  •         bindEvents: function() {
                this.show.onclick = this.sendData.bind(this, this.start_date, this.end_date);
            },
    
    1. By calling click you're simulating click on the button, not attaching event handler (this would work for jquery object but not for dom element)
    2. To "prepend" some parameters to your handler in addition to the event itself use bind