KnockoutJS计算未定义

时间:2014-04-21 20:33:30

标签: knockout.js

我有一个计算的observable,它有两个基于整数的observable,我试图把它变成一个时间跨度值。通过查看文档似乎应该很容易,但我得到一个未定义的:我计算的未定义值。如果这很难理解,请道歉。任何帮助深表感谢。这是我的JS:

var Routine = function (routine_name, minutes, seconds, duration, rest, rounds) {
    this.routine_name = ko.protectedObservable(routine_name);
    this.minutes = ko.protectedObservable(minutes);
    this.seconds = ko.protectedObservable(seconds);
    //this.duration = ko.protectedObservable(duration);
    this.rest = ko.protectedObservable(rest);
    this.rounds = ko.protectedObservable(rounds || 1);

    this.duration = ko.computed(function () {
        return this.minutes + ':' + this.seconds;
    });

} 

var RoutineModel = function (Routines) {

    var self = this;
    self.routine_id = ko.observable();
    self.routine_name = ko.observable();
    //self.duration = ko.observable();
    self.minutes = ko.observable();
    self.seconds = ko.observable();
    self.rest = ko.observable();
    self.rounds = ko.observable();
    self.workout_name = ko.observable();

    self.duration = ko.computed(function () {
        return self.minutes() + ':' + self.seconds();
    });

this.Routines = ko.observableArray(Routines);

this.selectedRoutine = ko.observable();

this.addRoutine = function () {

            var newRoutine = new Routine("new routine", 0, 0, 0, 0);
            self.Routines.push(newRoutine);
            self.selectedRoutine(newRoutine);

    };

this.acceptRoutineEdit = function () {
        var selectedRoutine = self.selectedRoutine();
        selectedRoutine.routine_name.commit();
        selectedRoutine.minutes.commit();
        selectedRoutine.seconds.commit();
        //selectedRoutine.duration.commit();
        selectedRoutine.rest.commit();
        selectedRoutine.rounds.commit();
        self.selectedRoutine(null);

        selectedRoutine.duration = ko.computed(function () {
            return selectedRoutine.minutes + ':' + selectedRoutine.seconds;
        });
    };
};

1 个答案:

答案 0 :(得分:1)

您的duration计算正在使用this并且正在使用错误的上下文进行计算。

当你定义computed时,你可以传入第二个参数来控制this的值,当你的计算被评估为:

   this.duration = ko.computed(function () {
        return this.minutes() + ':' + this.seconds();
    }, this);

您的其他计算,请勿使用this,因此似乎没有相同的问题。

此外,在此计算和selectedRoutine.duration计算中,请确保将observable调用为函数以检索其值,如:

return selectedRoutine.minutes() + ':' + selectedRoutine.seconds();