为计算的Observable Knockout.js设置默认值 [英] Setting default values for computed Observable Knockout.js

查看:60
本文介绍了为计算的Observable Knockout.js设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Knockout.js的新手 我在UI中有3个字段. 产品价值. 数量 总计

I am new to Knockout.js I have 3 fields in the UI . Product value. Quantity Total

一切都与计算得到的可观察值兼容,并且可以保存数据.出于某些业务原因,总数将在后端更改.

Everything works fine with the computed observable and could save the data.The total will be changed in the backend for some business reasons.

在取回数据时,我需要从数据库中显示总计作为初始值,但是当用户更改乘积和值时,应使用原始的计算函数.

While retrieving the data back,I need to show the total from the DB as initial value,but when the user chnages the product and value ,the original computed function should be used.

我尝试了bindingHandlers,但无法正确执行.

I tried bindingHandlers but could not get it right..

非常有帮助.

var TsFoundationDeviceModel = function(product,qty,total) {
    var self = this;
    self.product = ko.observable(product);
    self.quantity= ko.observable(qty);
    self.computedExample = ko.computed(function() {
        return self.product() * self.quantity() ;
    });
}

<input name="product" data-bind="value:product">
<input name="value" data-bind="value:value">
<input name="total" data-bind="value:computedExample"/>

推荐答案

唯一的方法是跟踪初始化程序.因此,第一次调用视图模型时,请将initialize设置为true,然后检查总数是否未定义.如果是这样,则返回合计,重置初始化.从那里开始,它将始终根据其他两个字段更新计算所得的值.

The only way you can do this is by keeping track of an initializer. So the first time you call your viewmodel, you set the initialize to true and check if the total is not undefined. If so, return total, reset initialize. From there on, it will always update the computed based on the other two fields.

这是相同的小提琴(顺便说一句,您的绑定中有错误,名称为值"的属性不存在,我认为它是数量

Here is the fiddle for the same (by the way, there is an error in your bindings, there is no property by the name "value", I assumed it is quantity

http://jsfiddle.net/sujesharukil/YTDZ9/

var TsFoundationDeviceModel = function(product,qty,total) {
    var 
    self = this;
    self.initialize = ko.observable(true);
    self.product = ko.observable(product);
    self.quantity= ko.observable(qty);
    self.computedExample = ko.computed(function() {
        var value = self.product() * self.quantity();
        if(self.initialize())
        {
            self.initialize(false);
            if(total != undefined && total != null)
                return total;
        }
        return value ;
    });
}


ko.applyBindings(new TsFoundationDeviceModel(1, 1, 3));

实际上,在您第一次创建视图模型的实例时,您将只返回一次合计.

in essensce, you will be returning total only once, the very first time you create an instance of your viewmodel.

希望这会有所帮助!

-Suj

这篇关于为计算的Observable Knockout.js设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆