0

我有一个视图模型如下:

    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>

我希望在执行 getPost 和 getPosts 函数时更新 post 对象和 posts 数组对象,但是 post 对象不会在 html 中更新,而 post 数组对象会在 html 中更新。

JsFiddle 在这里(http://jsfiddle.net/outia24/AVygn/)

我错过了什么吗?

4

1 回答 1

1

当你有一个 observable 时,例如:

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
于 2012-12-10T02:52:07.657 回答