[英]How to access ko.computed method of an observablearray in knockout js
self.work_days = ko.observableArray();
self.work_days().push(new WorkDayVM({}, new_date))//new_date is the date supplied from the form
function WorkDayVM(data, day) {
var self = this;
self.in_time1 = ko.observable();
self.out_time1 = ko.observable();
self.in_time2 = ko.observable();
self.out_time2 = ko.observable();
self.work_time = ko.computed(function () {
var in_time1_raw = self.in_time1();
var out_time1_raw = self.out_time1();
var in_time2_raw = self.in_time2();
var out_time2_raw = self.out_time2();
if(!in_time1_raw || !out_time1_raw || !in_time2_raw || !out_time2_raw)
return;
var t1 = get_minutes(in_time1_raw);
var t2 = get_minutes(out_time1_raw);
var t3 = get_minutes(in_time2_raw);
var t4 = get_minutes(out_time2_raw);
res = t2 - t1 + t4 - t3;
return get_hr_m(res);//returns hr:min
}, this);
}
console.log(self.work_days()[0].work_time); //prints dependentobservable()
console.log(self.work_days()[0].work_time());//prints undefined
I want to get work_time value. 我想获取work_time值。 How to access that value ?
如何获得该价值?
You are already accessing the work_time value correctly. 您已经在正确访问work_time值。
console.log(self.work_days()[0].work_time()); // prints undefined
The problem is in your WorkDayVM object. 问题出在您的WorkDayVM对象中。 It's not storing any data.
它不存储任何数据。 Your computed observable depends on a number of observables being filled with values, and if they aren't, it returns (undefined).
您计算出的可观察值取决于大量可观察值是否填充了值,如果没有,则返回(未定义)。 There is nothing in your code that uses the incoming parameters
data
and new_date
, so the observables your computed relies on are never filled. 您的代码中没有任何东西使用传入参数
data
和new_date
,因此永远不会填充您计算所依赖的可观察对象。
If you actually use the parameters coming into the WorkDayVM constructor to fill the observables in_time1, in_time2, out_time1 and out_time2, you will see that your console logs something else than undefined, and is actually working. 如果您实际使用WorkDayVM构造函数中的参数来填充可观察值in_time1,in_time2,out_time1和out_time2,则您会看到控制台记录了除未定义的内容之外的其他内容,并且它确实在工作。
In either case, I would change the return-statement in your computed observable to return something meaningful, if only null
. 无论哪种情况,我都将更改您所计算的observable中的return语句,以返回有意义的内容(如果仅为
null
。 Returning nothing from a computed observable is kind of bad practise, if you ask me. 如果您问我,从可计算的可观察值中不返回任何内容是一种不好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.