Reputation: 4108
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?
Upvotes: 0
Views: 171
Reputation: 3202
When you have an observable, such as:
var post = { title: ko.observable('test') } ;
You can update the value of the title like this:
post.title("New Title");
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:
var vm = (function() {
var self = this;
self.post = { title: ko.observable("test") } ;
return self;
})();
// This will cause "test" to show up in the HTML
ko.applyBindings(vm);
// Update the title in the viewmodel and HTML to "New Title"
// This is the proper way to update an observable.
vm.post.title("New Title");
// If you want to retrieve the value of an observable, you call
// it like a function, like this
var TheTitleOfMyPost = vm.post.title();
// This will break the binding, because you are creating a new
// object and pointing the post variable to the new object.
// The HTML, however, is still bound to the old object.
// Don't do it this way.
post = { title: ko.observable("Doesn't Work") }; // Initial Set
Upvotes: 1