Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Events vs. Callbacks In MVC Scenario

Tags:

javascript

I'm trying to work out a nice way to have views and controllers and minimize the ties between them.

Aside from multiple subscribers to one event, is there any major difference between js code like this:

var customers = {
    get: function(callback) {
        $.get('/customers', {}, function(data) { 
            callback.call(this, data); 
        });
    }
};

And an event-driven approach like this (event object is just pseudo code):

var customers = {
    get: function() {
        $j.get('/customers', {}, function(data) { 
            event.publish('customers.loaded', data); 
        });
    }
};

In both cases, the consumer of the customers object is ignorant of its inner workings. Does one way have an advantage over the other?

like image 968
Jason Finneyfrock Avatar asked Aug 24 '11 19:08

Jason Finneyfrock


2 Answers

Event's are callbacks, but the difference is when and where they're bound. In the first case, you need to have a reference to the callback at the time that get is called, additionally it's limited to a single callback.

In the second scenario, (assuming you're triggering an event with that pseudo-code) you could have bound a callback outside of the scope of where get is called, allowing for stronger data-encapsulation. Additionally, events support triggering multiple callbacks, so that different functions can be executed depending on what has had access to the customers object.

I'd recommend going with the event-oriented solution as JavaScript is an event-oriented language.

like image 150
zzzzBov Avatar answered Oct 21 '22 04:10

zzzzBov


The answer is quite straight forward : since an event may have unlimited event handlers(which are nothing but callbacks)... and a callback is just a single callback, I suggest that you go towards the event driven programming method.

like image 23
gion_13 Avatar answered Oct 21 '22 06:10

gion_13