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 関数が実行されると、投稿オブジェクトと投稿配列オブジェクトが更新されると予想していましたが、投稿オブジェクトは HTML で更新されませんが、投稿配列オブジェクトは HTML で更新されます。

JsFiddle はこちら(http://jsfiddle.net/outia24/AVygn/)

何か見逃しましたか?

4

1 に答える 1

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