I have been playing with event driven javascript lately, and have wondered if it's a good/bad thing for objects listening for their own events as a way of abstracting and simplifying internal logic.
Consider the following:
function MyModule(options) {
this.options = options;
this.data = {};
this.setListeners();
//...
}
MyModule.prototype = new EventEmitter;
MyModule.prototype.constructor = MyModule;
MyModule.prototype.updateBasket = function() {
var self = this,
url = this.options.url;
$.ajax(url)
.done(function(data) {
self.emit('basketupdate:success', data);
})
.fail(function(jqxhr, textStatus, err) {
self.emit('basketupdate:error', err);
})
.complete(function() {
self.emit('basketupdate:complete');
});
};
MyModule.prototype.setListeners = function() {
var self = this;
this.on('basketupdate:success', function(data) {
// ... do something on success
self.data = data;
});
this.on('basketupdate:success', function(data) {
// ... do something else on success
console.dir(data);
});
this.on('basketupdate:error', function() {
// ... do something to handle the error
});
};
var module = new MyModule({
url: '/path/to/request'
});
module.updateBasket();
A simple module with an ajax request. I could quite easily put all the logic in the corresponding callback, or even map callbacks to internal methods. However I'm quite liking this approach to simplifying the code.
Are there downsides or potential problems to structuring the code in the way that I haven't considered. Or would this be seen as an anti-pattern with events only intended to be listened to from elsewhere?
1 Answer 1
You could do this, but it's not really useful.
This code is just easier to read:
MyModule.prototype.updateBasket = function() {
var self = this,
url = this.options.url;
$.ajax(url)
.done(this.done)
.fail(this.fail)
.complete(this.complete);
};
MyModule.prototype.done = function(data) {
// Do something when done
};
MyModule.prototype.fail = function(data) {
// Do something when request failed
};
MyModule.prototype.complete = function(data) {
// Do something no matter what
};
And you could give more meaningful names to your methods.
Event emitters are useful when you're playing with different objects that you don't want to link together.