如何从knockoutjs更新对象的值?

时间:2015-06-04 08:42:21

标签: javascript jquery knockout.js

我正在使用knockoutjs将数据绑定到表,我想在用户点击时更新对象。这是我的代码

    var Books = [{Book:"Harry Potter",Author:"J.K rowling"},{Book:"5 Point Someone",Author:"Chetan Bhagat"},{Book:"I too had a love story",Author:"Ravinder Singh"}];

    var appViewModel = function() {
        this.firstName = ko.observable("Amit");
        this.Books = ko.observableArray([]);
        this.Books(Books);
        this.updateBook = function() {
            this.Book("Harry Potter and Prisoner of Azkaban");
        }
    };
    ko.applyBindings(appViewModel);                     

但它得到错误:“未捕获TypeError:字符串不是函数”。怎么解决它?

请参阅:http://jsfiddle.net/jVQY8/8/

1 个答案:

答案 0 :(得分:1)

您还需要将每个Book对象的属性设为observable。使用mapping插件(现在内置):

this.Books = ko.mapping.fromJS(Books);

此外,当每个this引用不同的对象时,看到这些this.updateBook = function(book) { book.Book("Harry Potter and Prisoner of Azkaban"); }; 有点误导。常见的方法是:

Enterprise Applications > {app_name} > Class loader

请参阅Fiddle