PeraMika
PeraMika

Reputation: 3688

Understanding jQuery & Pub Sub Pattern with this example

I use jQuery for some time, but that is usually very simple jQuery. I just watched some video tutorial in which the author uses something called Pub Sub Pattern. I've never heard of it before, so I have searched on Stackoverflow and Google for explanations:

But it's still not clear to me, especially because of the code that is used by the author of the above mentioned tutorial. So, I will paste this code here and if you can give me explanations:

1. Here is the first .js file named pubsub.js, and I don't understand it:

    (function($) {

        var o = $({});   // ??? what is this ???

        $.subscribe = function() {    // ??? and this ???
            o.on.apply(o, arguments);   // ??? o.on.apply(o, arguments) ???
        };

        $.unsubscribe = function() {   // ??? and this ???
            o.off.apply(o, arguments);   // ??
        };

        $.publish = function() {   // ??? and this ???
            o.trigger.apply(o, arguments);   // ?? o.trigger.apply(o, arguments); ??
        };

    }(jQuery));

I know that with jQuery you can use $( document ).ready() or $(function() but I've never seen (function($) { ... }(jQuery)); - what does this mean/do? Also, I don't understand the rest of the code...

2. The next file is app.js and it contains:

(function() {
    $.subscribe('form.submitted', function() {
        $('.flash').fadeIn(500).delay(1000).fadeOut(500);
    })
});

What does this actually do? Again, what (function() { ... }); means/do? And as for the rest of code, can you explain to me $.subscribe('form.submitted', function() {?

3. Finally, we have something like this:

 $.publish('form.submitted', form); // publish? 

This also is not clear to me.


I understand that all this is a basic implementation of PubSub Pattern with jQuery, but I still don't get why would someone do in this way (by using this pattern), I have read that answer on Stackoverflow, but it's still unclear to me... I guess that if I understand this code, then it would become clearer to me why and when to use this pattern.

Upvotes: 1

Views: 2059

Answers (1)

Paul Witschger
Paul Witschger

Reputation: 51

In the case of (function($) { ... }(jQuery));, the author is passing the jQuery instance in as a parameter. Inside the function (which has it's own scope), the $ is a reference to the jQuery instance that was passed in.

"Pub Sub" is just another term for Event Management, or Event Handling. All you're saying is "When [this] happens, do [that]".

When you "subscribe", you are passing in 2 parameters, the "event" that you are listening for, and the code you want to run when the event "fires".

When you "publish", you are "firing" (or triggering) that event.

Think of it like the onclick event. When you set something up on the onclick event, you are subscribing to that event. When you click, you are publishing that event.

Upvotes: 2

Related Questions