Knockout JS:传递给可写计算返回的值 [对象对象]

Knockout JS: Value passed to Writeable Computed returns [object Object]?

本文关键字:对象 返回 计算 JS Knockout      更新时间:2023-09-26

>Background

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

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

问题

当我试图放弃时,我的问题就出现了。我不相信我的可写计算结构是否正确,但我也不确定出了什么问题。 我注意到属性"n"和workType在我的read函数中正确给出,但在我的write中,它们不是预期的。例如,在read中,workType返回默认值 homework ,但在我的 write 函数中,它返回 [object Object]

能够澄清我的问题是什么并为我正确编写可写计算脚本的策略的回复将不胜感激。

相关的JS和HTML片段如下。

JSBin:完整项目

.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 (在表中输入。

我现在觉得自己很傻,但事实证明我走在正确的轨道上;事实上,解决方案非常简单。在 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;   
    },
    ...