2

If this is the equivalent to the jquery bind method, what would it be for the trigger method.

function bind( scope, fn ) {
    return function () {
        fn.apply( scope, arguments );
    };
}

the code above is from another post and it looks the same as a proxy method

you can comment on this too

I have to take the jquery part out off this framework, - this is just the relevant part

if (selector === '') {
              this.el.bind(eventName, method);
            } else {
              this.el.delegate(selector, eventName, method);
            }
          }
        }
      });

      if (includes) result.include(includes);

      return result;
    };

    exports.Controller = mod;
})($, window);

var exports = this;

var Events = {
    bind: function(){
      if ( !this.o ) this.o = $({});
      this.o.bind.apply(this.o, arguments);
    },
trigger: function(){
  if ( !this.o ) this.o = $({});
  this.o.trigger.apply(this.o, arguments);
}
};

thanks

Richard
  • 4,516
  • 11
  • 60
  • 87

2 Answers2

8

It depends on the type of event you wish to trigger. If it's a custom event:

var event = new Event('build');
elem.dispatchEvent(event);

If it's a native event:

var event = new MouseEvent('click');
elem.dispatchEvent(event);

This is of course meant to simulate a mouse event. Other events have their own type.

Naor Biton
  • 952
  • 9
  • 14
  • This is for custom events, right?- or non-browser javascript. I have no need for constructor functions. This confuses me. – Richard Jul 24 '13 at 14:15
  • The first case I presented is for custom events, the second one is for native browser events. You don't need to define these constructor functions, they're predefined by the browser for you to use. For some reason, you have to use these constructors to dispatch events, you can't just dispatch a plain string. There's a more detailed explanation at [MDN](https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Creating_and_triggering_events). – Naor Biton Jul 24 '13 at 15:36
  • thanks, because I am still working this out. The console is indeed telling me that there is no dispatch method on the object, I was also looking at the jquery source code, but that is not helping much yet. – Richard Jul 24 '13 at 16:30
  • 1
    was looking for this answer around 2hr, got it finally – Sharifur Robin Jun 24 '21 at 07:27
4

Once I crossed this site How to Manually Trigger Events in JavaScript

// Here is a VERY basic generic trigger method
function triggerEvent(el, type)
{
    if ((el[type] || false) && typeof el[type] == 'function')
    {
        el[type](el);
    }
}

// We could call this on multiple objects at any time
function resetFields()
{
    triggerEvent(document.getElementById('has-email'), 'onchange');
    triggerEvent(document.getElementById('other-field'), 'onclick');
    triggerEvent(document.getEleemntById('another-one'), 'onblur');
}
Praveen
  • 55,303
  • 33
  • 133
  • 164