dojo.provide("samples.widget.ChatWidget");
dojo.require("dojox.cometd");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare("samples.widget.ChatWidget", [dijit._Widget, dijit._Templated], {
templatePath: dojo.moduleUrl("samples", "widget/templates/ChatWidget.html"),
title: "Chat",
chatTopic:"",
chatName:"",
postCreate: function(){
dojox.cometd.subscribe(this.chatTopic,this, "receiveMessage");
this.chatName = "User" +(Math.floor(Math.random()*10000) + 1);
this.nameValue.value = this.chatName;
this._appendText(this.titleText, this.title);
dojox.cometd.publish(this.chatTopic, { user: this.chatName, operation:"new"});
},
receiveMessage: function(message){
var chatarea = dojo.byId(this.chatBox);
if (message.data.operation == "rename")
chatarea.innerHTML = chatarea.innerHTML + "<br><i>" + message.data.oldUser + " has changed names to " + message.data.user + ".</i>";
else if (message.data.operation == "new")
chatarea.innerHTML = chatarea.innerHTML + "<br><i>" + message.data.user + " has joined the chat.</i>";
else if (message.data.operation == "message")
chatarea.innerHTML = chatarea.innerHTML + "<br><i>" + message.data.user + ":</i> " + message.data.message;
chatarea.scrollTop = chatarea.scrollHeight;
},
sendMessage: function() {
dojox.cometd.publish(this.chatTopic, {message: this.chatText.value, user: this.chatName, operation:"message"});
this.chatText.value = "";
},
enterCheck: function(evt) {
if(evt.keyCode == dojo.keys.ENTER) {
this.sendMessage();
dojo.stopEvent(evt);
}
},
_appendText: function(node, text){
while(node.firstChild){
node.removeChild(node.firstChild);
}
node.appendChild(document.createTextNode(text));
},
changeName: function() {
if (this.nameValue.value == "") {
this.nameValue.value = this.chatName; // Attempted to specify as blank. Revert to original name
return;
}
if (this.nameValue.value == this.chatName)
return;
dojox.cometd.publish(this.chatTopic, { user: this.nameValue.value, oldUser:this.chatName, operation:"rename"});
this.chatName = this.nameValue.value;
}
}); |