【发布时间】:2015-08-19 06:35:48
【问题描述】:
我是淘汰赛 js 的新手。所以请看我下面的代码并告诉我哪个函数将被视为视图模型?
有两个函数,一个是CartLine,另一个是购物车............哪个函数将被视为视图模型?
查看此代码ko.applyBindings(new Cart());
应用绑定指向购物车功能.......那么这是否意味着cart() 将被视为视图模型?如果是,那么我们应该CartLine() 做什么?它是子视图模型还是嵌套视图模型?
寻求指导。代码取自这个 jsfiddle http://jsfiddle.net/3bu6nybk/15/
var CartLine = function () {
var self = this;
self.products = ko.observableArray(_products);
self.product = ko.observable(1);
self.price = ko.observable(1);
self.quantity = ko.observable(1);
self.product.subscribe(function(item){
if(!item)
{
self.price(0);
self.quantity(0);
return;
}
self.price(item.price);
self.quantity(item.quantity);
});
self.subtotal = ko.computed(function () {
return self.price() * self.quantity();
},self);
};
var Cart = function () {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
self.formatCurrency = formatCurrency;
};
【问题讨论】:
-
您的视图模型是您作为参数传递给
applyBindings()方法的对象。 -
@haim770 如果看到我发布的代码,那么你可以看到有两个函数叫做
CartLine & Cart。所以我的问题是哪个函数将被称为视图模型?两者都将被视为视图模型或将参数传递给ko.applyBindings()函数的模型?
标签: knockout.js