gpt4 book ai didi

javascript - ko.computed 在 ko.observableArray 上

转载 作者:行者123 更新时间:2023-11-30 08:54:02 26 4
gpt4 key购买 nike

我正在尝试使用计算来计算某些产品的总和。

function productViewModel(){

self = this;
function productModel(data)
{
var self=this;
self.id=ko.observable(data.id);
self.codigo=ko.observable(data.codigo);
self.recurso=ko.observable(data.recurso);
self.unidad=ko.observable(data.unidad);
self.precio_unitario=ko.observable(0);
self.cantidad=ko.observable(0);
self.total=ko.computed(function()
{
return self.precio_unitario()*self.cantidad();
},productModel);
}

self.products = ko.observableArray([]);

self.addProduct = function(product)
{
self.products.push(new productModel(product));
};
self.removeProduct = function()
{
self.products.remove(this);
};

}

orden = new productViewModel()
ko.applyBindings(orden);

但是当 precio_unitariocantidad 改变时。 total 不更新。

最佳答案

function productModel(data)
{
var self=this;
...
self.total=ko.computed(function()
{
return self.precio_unitario()*self.cantidad();
},this);
}

您应该将 ko.computed 绑定(bind)到 this 而不是函数。您希望它绑定(bind)到创建的对象,而不是绑定(bind)到构造函数,后者不会有这些属性。由于您使用的是 self,因此默认情况下会实际处理这一点,如果您愿意,可以完全省略第二个参数。

在构造函数中,thisself 将引用使用new 运算符时创建的对象。因此,所有属性都将在该对象上创建。

关于javascript - ko.computed 在 ko.observableArray 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15261690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com