I have a viewmodel as follow :
var PostModel = function(data){
ko.mapping.fromJS(data, {}, this);
};
var vm = (function () {
var post = {};
var posts = ko.observableArray([]);
var getPost = function () {
var tmp = {
title: new Date(),
content: new Date()
};
//post.title(tmp.title());
//post.content(tmp.content());
ko.mapping.fromJS(tmp, mappingOption, post);
};
var getPosts = function () {
posts.removeAll();
for (var i = 0; i < 2; i++) {
posts.push({ title: new Date() });
}
};
var mappingOption = {
create: function (options) {
return new PostModel(options.data);
}
}
return {
post : post,
posts : posts,
getPost : getPost,
getPosts: getPosts
};
})();
ko.applyBindings(vm);
and responding html as follow :
<button data-bind="click: getPost">get post</button>
<br />
<label data-bind="text: post.title" ></label>
<br />
<button data-bind="click: getPosts">get post list</button>
<ul data-bind="foreach: posts">
<li data-bind="text: title"></li>
</ul>
I expected post object and posts array object would updated when getPost and getPosts function excuted, however post object is not updated in the html while posts array object updated in the html.
JsFiddle is here (http://jsfiddle.net/outia24/AVygn/)
Did I miss anything?
When you have an observable, such as:
You can update the value of the title like this:
If you replace the title or if you replace post after the bindings are set up, then the binding get disconnected and you lose the binding. Here are some more samples: