Knockout JS:传递给Writeable Computed的值返回[object Object]?

时间:2014-05-28 23:50:56

标签: javascript html knockout.js ko.observablearray

背景

在进行正在进行的学习项目时,我注意到我需要一个可写的计算函数来解决我面临的问题。这是瘦的:我试图1)从成绩簿中删除用户指定数量的作业分数2)。

用户输入上面的值,然后点击按钮dropLowestScores。然后,代码将最低分数添加到名为“最低”的数组中,该数组存在于每个student对象上。 然后,根据新值更新每个学生的可观察mean,删除最低值。

问题

当我试图放弃时,我的问题变得生机勃勃。我不确定我的可写计算结构是否正确,但我也不确定是什么问题。我注意到我的workType函数中正确地给出了属性'n'和read,但在我的write中,它们并不理想。例如,在read中,workType会返回默认值homework,但在我的write函数中,它会返回[object Object]

可以澄清我的问题是什么的答案,并给我一个正确编写可写计算脚本的策略,我们将不胜感激。

相关的JS和HTML代码段如下。

  

JSBin Full Project

JS

this.dropLowestScores = ko.computed({

    // read the parameters necessary to write values to property 'lowest'

    read: function() {

        // user sets value of 'n' in the page via ko 'options'

        var n = _this.n().n;

        // user selects 'workType' from list of ko options            

        var workType = _this.workType().workType;
        console.log("workType:" + workType);
        return n,workType;   
    },

    // now use current parameter values to set new values to 'lowest' arrays 

    write: function(n,workType) {
        //this.n = n;
        //this.workType = workType;

        // 'lowest' exists as a property for each student, 
        // ergo, I loop through each student 

        ko.utils.arrayForEach(_this.students(), function(student){
            var i = _this.students.indexOf(student);

            console.log("_this.assignments: " + _this.assignments()[i].workType().workType);
            console.log("this.workType: " + this.workType);
            console.log(_this.assignments()[i].workType().workType == this.workType);

            // if the current assignment is the same as the user-specified assignment, 
            //add the score for that assignment to array 'tmp'; then set lowest = tmp 

            if(_this.assignments()[i].workType().workType == this.workType){
                var tmp = student.scores().sort(_this.comparator).slice(0,this.n);
                console.log(tmp.length);
                student.lowest(tmp);
            }    
        });
    }
});     

HTML

<button data-bind="click: dropLowestScores">Drop Lowest Scores</button>

目前,我只是将上述功能绑定到了一个按钮。理想情况下,我就是这样做的。引用的其他属性(例如nworkTypemean)将在表格中输入。

1 个答案:

答案 0 :(得分:0)

我现在觉得很傻,但事实证明我是在正确的轨道上;实际上,解决方案非常简单。在read函数中,我只需要按以下方式定义属性:this.variable = ...而不是var variable = ...

this.dropLowestScores = ko.computed({

    // read the parameters necessary to write values to property 'lowest'

    read: function() {

        // user sets value of 'n' in the page via ko 'options'

        this.n = _this.n().n;

        // user selects 'workType' from list of ko options            

        this.workType = _this.workType().workType;

        console.log("workType:" + workType);
        return n,workType;   
    },

    ...