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?