Buzzzzzzz
Buzzzzzzz

Reputation: 1214

JQuery where does the data come from?

I have seen many JQuery functions using parameter function parameters. Even though I use them, It feels rather incomplete without knowing how this work in the back end. as an example lets use the click method :

$("p").click(function(event){
    event.preventdefault();
    alert("testing 123");
});

In this code, if I used, "this" inside the method, it will give me the "p" element itself. However, I cannot figure out the "event" parameter get assigned with something. shouldn't there be some place with a code bit like

var event = blah blah;

so that the event parameter has some values?

I have clicked the actual JQuery file by pressing f12 and it goes to a function like this

jQuery.fn[ name ] = function( data, fn ) {
    return arguments.length > 0 ?
        this.on( name, null, data, fn ) :
        this.trigger( name );
};

I cannot see any place of that filling or assigning something to the parameter named "event"

I have the same problem with $.ajax requests as well,

$.ajax({
    type: "POST",
    url: url, 
    async: false,
    success: function (data) {  }
});

It is visible that there is someplace loading the "data" in the "data" parameter, How and where does the actual data get filled up in? when do we load actual data. I have seen a bit of similar problem.

Upvotes: 3

Views: 317

Answers (3)

Julien Grégoire
Julien Grégoire

Reputation: 17144

jQuery is basically a wrapper that returns an object with many methods. Most of them are not that straightforward, if you want to understand more deeply, you don't have many choices except using the console and going through the source code which you can find here: https://code.jquery.com/jquery-1.12.4.js. Ideally, use uncompressed version. For some methods, it can be quite long to get to the bottom of it. The way the Click callback works is hidden pretty deep.

You can find it this way:

In the console, enter $("p").click. You'll get:

ƒ ( data, fn ) {
        return arguments.length > 0 ?
            this.on( name, null, data, fn ) :
            this.trigger( name );
    }

Which comes from here in the source code:

jQuery.each( ( "blur focus focusin focusout load resize scroll unload click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup error contextmenu" ).split( " " ),
    function( i, name ) {

    // Handle event binding
    jQuery.fn[ name ] = function( data, fn ) {
        return arguments.length > 0 ?
            this.on( name, null, data, fn ) :
            this.trigger( name );
    };
} );

So because you have at least an argument, it runs: this.on( name, null, data, fn ), where this is your jQuery object $('p'), name is 'click', and data is your function(event). So onto this.on():

 console.log($('p').on);
    ƒ ( types, selector, data, fn ) {
            return on( this, types, selector, data, fn );
        }

Here, function on isn't global, so it's in jQuery's closure, so back to the source code where you can find:

 function on( elem, types, selector, data, fn, one ) {
    ...

where elem is your jQuery object $('p'), types is 'click', selector is null, data is your function(e) and fn is null. This leads to:

elem.each( function() {
        jQuery.event.add( this, types, fn, data, selector );
    } );

So you can find:

jQuery.event = {

    global: {},

    add: function( elem, types, handler, data, selector ) {
    ...

Where you can find an addEventListener :

elem.addEventListener( type, eventHandle, false );

On addEventListener, the callback has the event parameter, which is native javascript. In jQuery, the callback is eventHandle, so let's find this one:

eventHandle = elemData.handle = function( e ) {

                // Discard the second event of a jQuery.event.trigger() and
                // when an event is called after a page has unloaded
                return typeof jQuery !== "undefined" &&
                    ( !e || jQuery.event.triggered !== e.type ) ?
                    jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
                    undefined;
            };

So it returns the function dispatch, so now the callback is this : jQuery.event.dispatch.apply( eventHandle.elem, arguments ) , where arguments is e (the original addEventListener Event). So find dispatch:

 dispatch: function( event ) {

            // Make a writable jQuery.Event from the native event object
            event = jQuery.event.fix( event );
            ...

So what is this event.fix:

 fix: function( event ) {
            if ( event[ jQuery.expando ] ) {
                return event;
            }

            // Create a writable copy of the event object and normalize some properties
            var i, prop, copy,
                type = event.type,
                originalEvent = event,
                fixHook = this.fixHooks[ type ];

In here you find

  event = new jQuery.Event( originalEvent );

    jQuery.Event = function( src, props ) {
    ...

Where the event that is passed as a parameter of click is defined. You can test it by adding properties on jQuery.Event.prototype. Like this for example:

jQuery.Event.prototype.prop = 'newProp';

So, to sum up, the event in function(event), is an instance of jQuery.Event.

See

console.log($('p').click);
console.log($('p').on);
console.log(jQuery.Event)
jQuery.Event.prototype.prop = 'test';

$('p').click(function(event){console.log(event.prop)});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<p>test</p>

For Ajax, it's probably a bit more straightforward, but again, if you want to know exactly, not much else you can do but go through the source code.

Upvotes: 1

cela
cela

Reputation: 2510

In reference to your first question, about the event parameter, the event is your click. It will never be explicitly declared like a normal variable. It is just a parameter, and in your example the click is the event.

In reference to your ajax question, the data parameter is what is coming back from your backend after a successful post. For example, I use ajax calls to send some information from my frontend. My backend then uses that information to send back data to frontend inside that success: function(data), like JSON. JSON would be the data parameter.

Upvotes: 0

ryanpcmcquen
ryanpcmcquen

Reputation: 6475

The declaration happens in the function parameters themselves.

Declaring data, event, or whatever you want to call it inside the function parameters (any word will work), is effectively the var data = ... statement.

In the instance of an event handler, event is passed by the browser to any function latching on to that event. In the case of the ajax call, as @Alec said, that is the data returning from the server.

Upvotes: 1

Related Questions