0

You know the .on('eventName', function(){...}); pattern that exists within jQuery, socket.io, peerjs and a few other libraries/frameworks for event handling, what is it called?

I'd like to get a better idea of the structure behind the scenes, what it can do, whats really going on etc, but haven't been able to turn up much from Google searches, does the pattern have a name? did someone specific come up with this pattern?

From what I can gather so far it seems to be similar to addEventListener, are there any specific differences?

EDIT: Just to clear things up a little, I'm looking to implement some type of event handling into one of my Node JS applications and ideally want to be able to trigger events that will be caught like below, and was looking for research into best practice - just couldn't figure out good search terms etc.

var myNewObject = new MyLibrary();

myNewObject.on('event_1', function(param1, param2){

...

});

Thanks!

Jamie Street
  • 1,527
  • 3
  • 14
  • 32
  • 1
    https://api.jquery.com/on/ – Satpal Apr 01 '14 at 09:15
  • It's called a function with two arguments ? – adeneo Apr 01 '14 at 09:16
  • Event callback pattern -- as seen [here](http://stackoverflow.com/questions/8951276/callback-command-vs-eventlistener-observer-pattern). Whenever you pass a function as a parameter that's considered a "callback" while the event handling stuff is pretty standard, just a bit focused on simplicity of definition. – Mihai Stancu Apr 01 '14 at 09:17
  • @Satpal it is obvious he's not referring to the `jQuery.on()` function. @adeneo that would be a very rought oversimplification his 3 paragraphs of explanations. – Mihai Stancu Apr 01 '14 at 09:19
  • refer this https://learn.jquery.com/events/event-delegation/ – Kiranramchandran Apr 01 '14 at 09:20
  • @MihaiStancu - It's not really an oversimplification, it's just a function with two arguments, the latter argument being a function, and it's chainable because it's a property of some object. It's all very basic, it just looks a little strange at first. – adeneo Apr 01 '14 at 09:24
  • 1
    @OP - For node, you'd generally use the [EventEmitter](http://nodejs.org/api/events.html) class for this, not roll your own. – adeneo Apr 01 '14 at 09:25
  • @MihaiStancu you're right, I'm essentially trying to copy what they have done in jQuery, for my own libraries - without including jQuery, but am looking to figure out if there are any best practice, discussions surrounding that way of doing things. – Jamie Street Apr 01 '14 at 09:26
  • 1
    @adeneno -- I know that the `jQuery.on()` function is just a function with two arguments one is a string and one is a function. But I'm pretty sure that OP also knows this -- that's why I said it's an oversimplification. OP didn't ask that at all, OP wants to know "How do you call this event drive callback based architecture by a simple name." -- so he can Google search by using that name and learn more about it. – Mihai Stancu Apr 01 '14 at 09:32
  • @JamieShanikwaStreet in most cases a particular framework will implement a particular design pattern in their own unique way. This is because design patterns are not set in stone -- they have a generic idea and structure but implementations and behaviors will differ. – Mihai Stancu Apr 01 '14 at 09:33
  • @MihaiStancu I see, looks like I'll have to get my hands dirty and rip a few of them apart to see how they do things behind the scenes - cheers! – Jamie Street Apr 01 '14 at 09:35
  • @JamieShanikwaStreet That's why you have to research using that framework's name.`jQuery event handlers`. The trick in this becomes tweaking your query to avoid often searched **framework usages** and enhance finding **framework design**. – Mihai Stancu Apr 01 '14 at 09:36
  • @MihaiStancu - It doesn't have a name, as it's not a pattern, how hard can it be to grok ? – adeneo Apr 01 '14 at 09:44
  • @adeneo -- This is a pattern. It's an Observer pattern. jQuery implemented it their own way -- meaning Observers are not objects, they are just callbacks. Also observer registration is dynamic (you can add/remove observers anytime) not fixed. – Mihai Stancu Apr 01 '14 at 09:51
  • Just because it doesn't have a name doesn't mean people don't try to find a name for it. – Mihai Stancu Apr 01 '14 at 09:52
  • It would indeed fall under the Observer Pattern, but so would almost anything in javascript using callbacks, promises or events. – adeneo Apr 01 '14 at 10:09

3 Answers3

1

If you roll your own this is one way to do it:

notJQuery = function() {
    if (typeof(notJQuery.eventList) === 'undefined') {
        notJQuery.eventList = {};
    }

    this.on = function(events, callback) {
        events = events.split(' ');
        for (i in events) {
            eventName = events[i];
            notJQuery.eventList[eventName][] = callback;
        }
    };

    return this;
};

You need an event list to hold all of the eventName => callback association.

Every time you want to trigger an "artificial" event (an event designed by you) you lookup the event list and find all the callbacks for that event.

Every time you update the event handlers for a real event (not designed by you) you lookup the event list and attach those callbacks for that event to the system-provided event handler/listener.

Mihai Stancu
  • 15,848
  • 2
  • 33
  • 51
1

It's not really a pattern, it really is just a function with two arguments.

Generally you start by having a main object, jQuery uses $, and you return a new instance of that object.

Then you attach properties, like on(), that are functions that accept arguments, just like any other function.

Very simplified it looks like this

var $ = function(selector) {
    if (!(this instanceof $)){
        var instance = new $;
        instance.elem = document.querySelector(selector);
        return instance;
    }else{
        return this;
    }
}

$.prototype.on = function(event, callback) {
    this.elem.addEventListener(event, callback, false);
}

$('#test').on('click', function() {
    alert('This is how it works')
});

FIDDLE

And I just created something that looks just like jQuery in two minutes. Of course it's missing a few thousand lines of code and is rather limited, but it shows how this work, and that it's just objects and functions, that doesn't really have a special pattern.

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

It is called observable pattern and is used to subscribe to events and / or methods of a javascript object or plugin.

They are similar with callbacks, but with subscriber pattern you can subscribe / unsubscribe individually, and not having to put all logic inside one callback function.

Look on Emitter plugin

Catalin
  • 11,503
  • 19
  • 74
  • 147