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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With