Knockoutjs.com - Hello World Example
http://knockoutjs.com/examples/helloWorld.html
HTML
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<div id='boxchat' data-bind="foreach: ChatHistory">
<span data-bind="text: message" ></span>
</div>
<div id="txtArea">
<textarea data-bind="event:{keypress: $root.OnKeyPress}" name="chatinput" id="chatinput" ></textarea>
<br>
<input type="button" id="button" value="new message from server" />
</div>
CSS
body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; font-weight: bold; font-size: 1.2em; }
JavaScript
function ChatViewModel() {
self = this;
self.ChatHistory = ko.observableArray([new ChatMessage("testuser","testmessage")
]);
self.OnKeyPress = function (data, evt) {
if (evt.which === 13) {
self.ChatHistory.push(new ChatMessage("testvisitor", $('#chatinput').val()));
}
else
return true;
}
}
function ChatMessage(username, message) {
var self = this;
self.username = username;
self.message = message;
}
$("#button").click(function(){
chatVM.ChatHistory.push(
new ChatMessage("test","message from server")
);
});
var chatVM=new ChatViewModel();
ko.applyBindings(chatVM);