Benvenuti da Idea R | Vicenza - Romano di Lombardia (Bergamo)

Blog

Prendere uno smanettone del software degli anni 80, aggiungere un graphic designer di nuova generazione e allungare il tutto con uno studioso di strategie di marketing. Agitare energicamente e si ottiene il blog Idea R.

jQuery: how to throw and handle custom events

Pubblicato il 11/22/2012
Categorie: Siti Web
jQuery: how to throw and handle custom events

Questo articolo è disponibile anche in italiano.

We've already seen in a previous article how to manage JavaScript events.
jQuery simplifies but most of all uniforms the JavaScript events engine with 2 simple methods: bind() for events subscription and trigger() to fire them.

Events are not only a prerogative of standard DOM (Document Object Model) objects, your custom objects can throw events too, event if they aren't DOM objects.
In general, with jQuery you subscribe to events using the following form

$(mySelector).bind('click', function(event){...});

or the shorter

$(mySelector).click(function(event){...});

As mentioned above you can also subscribe to custom events, with

$(mySelector).bind('mycustomevent', function(event){...});

which in turn will be launched by the custom object using

$(mySelector).trigger('mycustomevent');

Question: can I pass data to the event handler at the time of binding?
Answer: you can pass any information specifying it in the bind method and the event handler will retrieve it from the data property of the event object.

// Use myCustomData to hold bind-time data
$(mySelector).bind('mycustomevent', myCustomData, function(event)
{
    ...

    // event.data contains myCustomData
    var myData = event.data;

    ...
});

One more question: can I pass data to the event handler at trigger-time?
Answer: simply define an additional parameter in your event handler.

// Use myParam to hold trigger-time data
$(mySelector).bind('mycustomevent', function(event, myParam){...});
...
$(mySelector).trigger('mycustomevent', 'this is the trigger-time parameter');

Sei il lettore numero 12,039.

Commenti

Articolo precedente

Articolo precedente

Il mondo dei social media 2013

Articolo successivo

3 methods to detect mobile devices in ASP.NET

Articolo successivo