Skip to content

Instantly share code, notes, and snippets.

@raphaeleidus
Created July 26, 2012 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphaeleidus/3183466 to your computer and use it in GitHub Desktop.
Save raphaeleidus/3183466 to your computer and use it in GitHub Desktop.
Using Event Listeners to create observer pattern
// Custom Events Used:
// { type: "privateMessages_newConversation", messages: {}, partner: {} }
// { type: "privateMessages_newMessage", message: {} }
// { type: "privateMessages_conversationListLoaded", payload: {} }
var PrivateConversation = function(event_id, recipient_hash, url) {
this.partner = recipient_hash;
this.event_id = event_id;
this.messager_id = recipient_hash.messager_id;
this.messager_type = recipient_hash.messager_type;
this.url = url;
};
_.extend(PrivateConversation.prototype, PP.mixins.JsonRequest); //attach mixins before main functions so functions can override if needed
_.extend(PrivateConversation.prototype, {
getMessages: function() {
var that = this;
this.getJSON({ 'event_id': this.event_id, 'messager_id': this.partner.messager_id, 'messager_type': this.partner.messager_type }, 'GET',
function(response){
that.messages = response.private_messages;
$.event.trigger({ type: "privateMessages_newConversation", messages: that.messages, partner: that.partner });
});
}
}
var ConversationView = function(options) {
var that = this;
$(document).on("privateMessages_newConversation", function(e){
that.messages = e.messages;
that.partner = e.partner;
that.render();
});
};
@akahn
Copy link

akahn commented Jul 26, 2012

My only feedback here would be that since jQuery's event system allows you to namespace events (with a dot, I think), you should use that. This allows listeners to listen by namespace in addition to listening for specific events.

@raphaeleidus
Copy link
Author

So instead of

// { type: "privateMessages_newConversation", messages: {}, partner: {} }
// { type: "privateMessages_newMessage", message: {} }
// { type: "privateMessages_conversationListLoaded", payload: {} }

we would have

// { type: "newConversation.privateMessages", messages: {}, partner: {} }
// { type: "newMessage.privateMessages", message: {} }
// { type: "conversationListLoaded.privateMessages", payload: {} }

that does look better, the problem is, if someone somewhere does
$(document).on( "newConversation", function(e){...} );
they will get all the actions intended for "newConversation.privateMessages"

@akahn what do you think about the trade off here?

@akahn
Copy link

akahn commented Jul 26, 2012

@raphaeleidus, isn't that the idea? Listeners can subscribe to all 'newMessage' events or only the ones within the 'privateMessages' namespace.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment