tags:

views:

7013

answers:

3

I'm looking for some input on how to implement custom eventhandling in jquery the best way. I know how to hook up events from the dom elements like 'click' etc, but I'm building a tiny javascript library/plugin to handle some preview functionality.

I've got a script running to update some text in a dom element from a set of rules and data/user input I got, but now I need that same text shown in other elements that this script can't possibly know of. What I need is a good pattern to somehow observe this script producing the needed text.

So how do I do this? Did I overlook some builtin functionality in jquery to raise/handle user events or do I need some jquery plugin to do it? What do you think is the best way/plugin to handle this?

+2  A: 

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });
Tuxified
I'm looking for a way to raise an event and have subscribers/listeners trigger on it. Not trigger it manually since the raising object doesn't know who are listening...
Per Hornshøj-Schierbeck
+14  A: 

take a look at this

Trigger and Bind What is exciting though (or at least what is exciting me) is the method by which the status gets relayed through the application. I’ve stumbled upon a largely un-discussed method of implementing a pub/sub system using jQuery’s trigger and bind methods.

vitorsilva
Excatly what i was looking for. He is probably right that it's the way to go, but i can't help thinking jquery need either direct support or a plugin to handle it more gracefully. I'll wait a bit and see if there are other takes on the problem before i flag an answer :)
Per Hornshøj-Schierbeck
+5  A: 

From: http://www.reynoldsftw.com/2009/04/custom-events-in-jquery-open-doors-to-complex-behaviors/

A quick recap of .bind() and .trigger()

$('body').bind('foo', { 'bar' : 'bam' }, function(e) { alert(e.data.bar); });
$('body').trigger('foo'); // alerts 'bam'

You can also pass params

$('body').bind('foo', function(e, param1, param2) { alert(param1 + ': ' + param2); });
$('body').trigger('foo', [ 'bar', 'bam' ]); // alerts 'bar: bam'
Chris Jacob