How can I put parametres into JQuery.Event data property and trigger it?

241 Views Asked by At

The goal is to pass parametres through event.data, here is complete example where I tested it : http://jsfiddle.net/

$el.trigger( $.Event('click.NGB', { example: '1' }));
$el.trigger( $.Event('click.NGB', {data: { example: '2' } })); // :-(
$el.trigger( $.Event('click.NGB', [{ example: '3' }]));
$el.trigger( $.Event('click.NGB', [{ data: { example: '4' } }])); 
$el.trigger( $.Event('click.NGB'), { example: '5' });
$el.trigger({ type: 'click.NGB', data: [{ example: '6' }] }); // :-(

I don't know why if an Event object has a data property we can't access it...

But with '.on' function it's works! :-(

$('#response').on( 'click.NGB', {example: '7'}, function(e){ e.data.example; } );  

Anyone know how to do? :-)

ANSWER

After all documentation and tests, I've decided use this method :

$el.trigger('click.NGB', [ {example : '8'} ] );

Thanks to all!

3

There are 3 best solutions below

1
On BEST ANSWER

This is a duplicate question of this question.

The "Short Answer" on that question should answer your question quite nicely.

Can trigger() pass data to your event handlers? Yes (as additional parameters)

Can trigger() pass data into the event.data object directly? No (only on() does this)

1
On

If your goal is to send extra data along with the event, you do that with additional parameters, both where you send and receive the event:

Receiving:

// Note discrete param --------------v
$("#foo").on("whatever", function(e, param) {
  display("param: " + JSON.stringify(param));
});

Sending:

// Note discrete param -------v
$("#foo").trigger("whatever", 42);

Live Example

3
On

Fixed here - http://jsfiddle.net/xgf1uhd1/7/

$('#button').on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();

    $el = $('#response');

    $el.trigger( $.Event('click.NGB', { example: '1' }));
});

$('#response').on('click.NGB', function () {
    $ev = arguments[0];
    example = arguments[1];
    $this = $(this);
    $this.find('pre').append('value is === ' + arguments[0].example);
});