<div class="commentBox">
<img src="http://icons.iconarchive.com/icons/custom-icon-design/valentine/256/heart-icon.png"/>
<div class="commentList">
<div class="comment" data-bind="foreach:comments">
<h2 class="commentAuthor" data-bind="text:author">
</h2>
<span data-bind="html:text">
</span>
</div>
<form name="commentForm" class="commentForm" data-bind="with:newComment">
<input type="text" data-bind="value:author" required/>
<input type="text" data-bind="value:text" required />
<button type="button" data-bind="click:$parent.addComment">Add</button>
</form>
</div>
</div>
スクリプト ファイル:
ko.validation.rules.required.message = 'Required Field.';
ko.validation.configure({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
var shayJS = (function ($, ko) {
//A simple promise returning DAL
var DAL = {};
DAL.insert = function (api, payload) {
return $.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: {
json: "{}"
}
});
};
DAL.get = function (api, payload) {
return $.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: {
json: JSON.stringify([{
author: '',
text: ''
}, ])
}
});
};
//Knockout Model
function CommentViewModel() {
var self = this;
//Comment Class
function Comment() {
var self = this;
self.author = ko.observable().extend({
required: true
});
self.text = ko.observable().extend({
required: true
});
ko.validation.group(self);
}
self.newComment = ko.observable(new Comment());
self.comments = ko.observableArray([]);
self.addComment = function () {
if (self.newComment().errors().length === 0) {
//Save the comment to the server
DAL.insert("comment", ko.toJSON(self.newComment()))
.done(self.afterSave);
} else {
self.newComment().errors.showAllMessages();
}
};
self.afterSave = function () {
//Add to the List
self.comments.push(self.newComment());
//Re Initialise the new Comment
self.newComment(new Comment());
};
//get comments from server
self.getLatestComments = function () {
return DAL.get("comment", {});
};
//Initialize the comment list, call server and update comments array
self.getLatestComments().done(self.comments);
}
ko.applyBindings(new CommentViewModel());
}($, ko));
デモ