JQuery uses my data in a custom event for specific property names

Wherein:

$(document.body).on( 'myevent', function (ev) { console.log(ev.data, ev.result); } ); $(document.body).trigger( $.Event( 'myevent', { data: 'foo', result: 'bar' } ) ); 

The console returns [null, undefined] . Was it expecting something? I found this to be troubling since there is no original event to copy the properties and I am running out of property names to send the server response.

ref: http://api.jquery.com/trigger/

ref: http://api.jquery.com/category/events/event-object/

A note about documents describes this behavior. If someone knows why and explain the jQuery source code, that would be great; we could indicate an error if this is something unexpected.

+4
source share
3 answers

The ev.data property is the data passed in the .on() call and nothing is passed, so it returns null . The data property added to your $.Event call is overwritten with null . Do not use the property names mentioned here for your custom data name: http://api.jquery.com/category/events/event-object/

+5
source

What about

 $(document).on('myevent',"body",function (ev,x) { console.log(x.data); console.log(x.result); } ); $(document.body).trigger('myevent',{data:'foo',result: 'bar'}); 

http://jsfiddle.net/ZbBAh/17/

+5
source

I don’t know who this can help, but at least once I found myself with mixed code that looks like this:

 ... .trigger('myevent', $.Event('myevent', {data: 'foo',result: 'bar'}))' 

i.e. both provide the event name as a parameter for .trigger and provide the user object ** user data ** to the event object.

The code must be either

 ... .trigger($.Event('myevent', {data: 'foo',result: 'bar'}))' 

or

 ... .trigger('myevent', {data: 'foo',result: 'bar'})' 

of course, they are not identical in where you get the data in the event handler, but at least they both work ...

0
source

Source: https://habr.com/ru/post/1389783/


All Articles