简体   繁体   English

在ko.observableArray上计算ko。

[英]ko.computed on an ko.observableArray

I'm trying to use a computed to calculate the total of some product. 我正在尝试使用计算机来计算某些产品的总数。

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);

But when precio_unitario and cantidad are changed. 但是,当precio_unitariocantidad更改时。 total doesn't update. total不会更新。

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

You should be binding the ko.computed to this not to the function. 你应该结合ko.computed到this不是功能。 You want it to be bound to the object thats created, not to the constructor, which won't have those properties on it. 您希望将其绑定到创建的对象上,而不是绑定在上面没有这些属性的构造函数上。 Since you're using self, this will actually be taken care of by default, and if you like you can omit the second argument entirely. 由于您使用的是self,因此默认情况下会自动进行处理,如果您愿意,可以完全省略第二个参数。

Within the constructor function, this or self will refer to the object that is created when you use the new operator. 在构造函数中, thisself将引用使用new运算符时创建的对象。 So all the properties will be created on that object. 因此,所有属性都将在该对象上创建。

self = this; should be var self = this; 应该是var self = this; ; ; otherwise you're overwriting the global self . 否则,您将覆盖全局self Also take out ,productModel on the computed; 还要在计算中取出,productModel ; it's not necessary. 这不是必需的。

Important parts: 重要部分:

function productViewModel() {
    var self = this;

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

Also it's important make sure you're always using the correct format for writing to observables. 同样重要的是要确保您始终使用正确的格式来写入可观察对象。 It should be self.catidad(newValue); 它应该是self.catidad(newValue); and not self.catidad = newValue; 而不是self.catidad = newValue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM