3
\$\begingroup\$

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?

asked May 25, 2013 at 13:58
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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.

answered May 25, 2013 at 14:04
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.