Created
July 26, 2012 17:51
-
-
Save raphaeleidus/3183466 to your computer and use it in GitHub Desktop.
Using Event Listeners to create observer pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}); | |
}; |
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?
@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
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.