如何在knockoutjs中使用原型对象的实例而不是JSON

时间:2014-07-17 08:27:20

标签: javascript json knockout.js

在Knockout JS示例@ http://knockoutjs.com/examples/gridEditor.html

在视图模型中,我们有以下代码

self.addGift = function() {
    self.gifts.push({
        name: "",
        price: ""
    });
};

var viewModel = new GiftModel([
    { name: "Tall Hat", price: "39.95"},
    { name: "Long Cloak", price: "120.00"}
]);

问题是匿名JSON对象。有什么方法可以传递一个类的实例并让它工作吗?比如使用new Gift()

self.addGift = function() {
        self.gifts.push(new Gift());
    };

var viewModel = new GiftModel([
    new Gift(){ name: "Tall Hat", price: "39.95"},
    new Gift(){ name: "Long Cloak", price: "120.00"}
]);

1 个答案:

答案 0 :(得分:1)

哦,我的...... 考虑这个http://jsfiddle.net/UZJL7/ 首先创建礼物模型然后

function Gift(opts){
 this.name= ko.observable(opts.name)
 this.price= ko.observable(opts.price)
}

并在括号内移动参数

  new Gift({ name: "Tall Hat", price: "39.95"}),
  new Gift({ name: "Long Cloak", price: "120.00"})