Created
February 22, 2012 01:42
-
-
Save nlacasse/1880520 to your computer and use it in GitHub Desktop.
Start chat
This file contains hidden or 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
spire.subscribe('spire.io chat example', {orderBy: 'asc'}, function (messages) { | |
// We want the oldest message at the top. | |
messages.reverse(); | |
$(messages).each(function(i, rawMessage){ | |
var message = rawMessage.content | |
, date = new Date(rawMessage.timestamp) | |
, mentionedRegex = new RegExp([ '(^|\\s|\\t)' | |
, currentUser | |
, '(\\s|\\t|:|-|,|$)' | |
].join(''), 'gi') | |
, content | |
, selector | |
, messageElement | |
; | |
// Add some helpers to the message object so the template can add | |
// some style hooks (classes). | |
message.isYou = message.author === currentUser; | |
message.cssID = 'message-' + message.id; | |
message.humanTime = [ date.getHours() | |
, ':' | |
, ('0' + date.getMinutes()).slice(-2) | |
].join(''); | |
// Create a DOM element using the Mustache template (don't add it to | |
// the page yet!). | |
messageElement = $(ich.message(message)); | |
// If the `chat.currentUser` is mentioned make sure to add a special | |
// class to it. | |
if ($(messageElement).find('.body').html().match(mentionedRegex)){ | |
var html = $(messageElement).find('.body').html() | |
, content = html.replace(mentionedRegex, [ '$1' | |
, '<span class="mention">' | |
, currentUser | |
, '</span>$2' | |
].join('')) | |
; | |
$(messageElement).find('.body').html(content); | |
} | |
// Alright, done messing around lets add the `messageElement` to the | |
// page and scroll to it, (saving this step to the end helps keep | |
// the reflows down). | |
$('.messages').append($(messageElement)).scrollTo($(messageElement)); | |
}); // $(messages) | |
}); // spire.subscribe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment