3

I learned how to develop in Javascript using the YUI 2 library and was wondering if there were a jQuery equivalent of Custom Events (http://developer.yahoo.com/yui/event/#customevent)

Specifically, I want to be able to define custom events without having to attach the listeners initially.

In YUI, I would create a page class and declare different custom events that can be subscribed to. Below is some example code to demonstrate what I want to do, but with jQuery

function ListPage() {
    var me = this;
    this.initEvent = new YAHOO.util.CustomEvent("initEvent");

    this.init = function() {
         // initialize events, DOM, etc
         this.initEvent.fire(me);
    }
}

In application Javascript, I would then like to subscribe to the initEvent.

var page = new ListPage();
page.initEvent.subscribe(
    function (type, args) {
        // do stuff here
    }
);

page.init();

Are there any tutorials/examples of something like this in jQuery?

I understand I can do something similar using bind() and trigger(), but the impression I get is I have to pass in an event handler when I call bind().

Is it possible in jQuery to create the custom event, but pass in the event handler later?

I hope my question makes sense. thanks!

Abe
  • 6,386
  • 12
  • 46
  • 75

1 Answers1

7

There are lots of pub/sub plugins for jquery.

Example - Rebecca Murphy screencast

Plugins - Ben Almans pubsub, Phiggins pubsub

redsquare
  • 78,161
  • 20
  • 151
  • 159
  • The screencast by Rebecca Murphy covers exactly what I was looking for. thank you! – Abe Jan 06 '11 at 23:08
  • Just wanted to added that the Phiggins pubsub plugin is absolute amazing! – Abe Jan 11 '11 at 03:10
  • It seems the link to Rebecca Murphy's screencast is dead. I tried to find it but didn't have any luck. I think the video is published here: http://net.tutsplus.com/tutorials/javascript-ajax/loose-coupling-with-the-pubsub-plugin/ , though, I think the reccomended implementation is this one currently: https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js – blong May 01 '12 at 17:30