NewProgrammer
NewProgrammer

Reputation: 7

How is an event passed in this scenario?

Teaching myself jQuery and I came across the code below. I wanted to know how the event was passed through the anonymous function without creation.

$(function() 
{
   $("#cancelForm").on("click", function(e)
    {
      e.preventDefault();
      clearForm();
    }
 });

Upvotes: 0

Views: 110

Answers (3)

Ele
Ele

Reputation: 33726

jQuery's event

jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.

Those properties are all documented, and accompanied by examples, on the Event object page.

The standard events in the Document Object Model are: blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, and keyup. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any.

You can check the caller function from Jquery calling the following console.log(arguments.callee.caller.toString()); within your click event.

That log prints the following:

function (a) {
    a = n.event.fix(a);
    var b, c, e, f, g, h = [],
        i = d.call(arguments),
        j = (L.get(this, "events") || {})[a.type] || [],
        k = n.event.special[a.type] || {};
    if (i[0] = a, a.delegateTarget = this, !k.preDispatch || k.preDispatch.call(this, a) !== !1) {
        h = n.event.handlers.call(this, a, j), b = 0;
        while ((f = h[b++]) && !a.isPropagationStopped()) {
            a.currentTarget = f.elem, c = 0;
            while ((g = f.handlers[c++]) && !a.isImmediatePropagationStopped()) (!a.namespace_re || a.namespace_re.test(g.namespace)) && (a.handleObj = g, a.data = g.data, e = ((n.event.special[g.origType] || {}).handle || g.handler).apply(f.elem, i), void 0 !== e && (a.result = e) === !1 && (a.preventDefault(), a.stopPropagation()))
        }
        return k.postDispatch && k.postDispatch.call(this, a), a.result
    }
}

So, basically, JQuery injects the event object applying the necessary data for your logic.

var clearForm = function() {
  console.log("Cleared");
};

$(function() {
  $("#cancelForm").on("click", function(e) {
    console.log(arguments.callee.caller.toString());

    e.preventDefault();
    clearForm();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='cancelForm'>
Cancel!
</button>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

As mentioned in comments the function you pass to on() as argument gets called inside on() where the event object is passed to your callback when the event actually occurs

Simplified example:

function dummyOn( eventName, callback){
   // do internal stuff

   // call the function you created and pass `100` to it
   // in real on() this would get called when event occurs and pass the event object
   callback(100);
}


dummyOn('silly-event', function(e){
  console.log('e=', e);// 100 from what was passed to callback when it is called
})

Upvotes: 0

Angel Politis
Angel Politis

Reputation: 11313

The event instance is passed internally by jQuery. In simple terms, when they define their on method, they execute the function you give passing the event as an argument when the specified event is triggered.

Example code:

(aiming to approximate how on would be defined)

/* Definition of the 'on' method'. */
$.fn.on = function (eventType, callback) {
   /* Iterate over every element of the jQuery object. */
   for (var i = 0, l = this.length; i < l; i++) {
      /* Create an event listener for the currently iterated element. */
      this[i].addEventListener(eventType, function (e) {
         /* Execute the callback given passing the custom jQuery Event object to it. */
         callback($.Event(e));
      });
   }
});

Notes:

  1. $.fn is the object where jQuery defines its prototype methods.
  2. The e shown in the function passed to addEventListener is passed by the browser.

Upvotes: 2

Related Questions