0
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 

我想獲取work_time值。如何訪問該值?如何訪問ko.computed在knockout js中觀察數組的方法

+0

是否有任何數據被推入'WorkDayVM'?在你的例子中,向你的'WorkDayVM'推入一個空的'data'對象會導致計算出的'work_time'返回一個未定義的。 – rwisch45

回答

0

您已經正確訪問work_time值。

console.log(self.work_days()[0].work_time()); // prints undefined

的問題是在你的WorkDayVM對象。它不存儲任何數據。你的計算觀察值取決於許多觀察值被填充值,如果它們不是,它返回(未定義)。您的代碼中沒有任何內容使用傳入參數datanew_date,因此您的計算所依賴的觀察值永遠不會被填充。

如果實際使用竄進WorkDayVM構造函數的參數,以填補觀測in_time1,in_time2,out_time1和out_time2,你會看到你的控制檯日誌的東西比其他不確定,並且正在工作。

在任何情況下,我會改變返回語句在你的計算觀察到如果只null返回有意義的事。如果你問我,從計算的可觀察數中不返回是一種不好的做法。

相關問題