如何在viewmodel上更新单个对象?

时间:2012-12-10 02:24:59

标签: knockout.js

我有一个viewmodel如下:

    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);​

并回复html如下:

<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>

我预计post对象和posts数组对象会在getPost和getPosts函数被执行时被更新,但是html中的post对象没有更新,而在html中更新了posts数组对象。

JsFiddle是here(http://jsfiddle.net/outia24/AVygn/)

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

当你有一个可观察的时候,例如:

var post    = { title: ko.observable('test') } ;

您可以像这样更新标题的值:

post.title("New Title");

如果替换标题或者在设置绑定后替换帖子,则绑定将断开连接并丢失绑定。以下是一些样本:

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