Knockout JS:传递给可写计算返回的值 [对象对象]
Knockout JS: Value passed to Writeable Computed returns [object Object]?
>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>
目前,我只是将上述功能绑定到一个屁股上。理想情况下,这就是我离开它的方式。引用的其他属性(如 n
、workType
和 mean
(在表中输入。
我现在觉得自己很傻,但事实证明我走在正确的轨道上;事实上,解决方案非常简单。在 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;
},
...
相关文章:
- Javascript:firstChild对象返回undefined
- Javascript对象返回垃圾值
- 从js中的对象返回一个值
- 从Javascript类对象返回函数
- 从具有最高值的对象返回属性
- 为什么我的Date对象返回当前日期
- NodeJS fs.readdr-将回调内部作为对象返回
- Leadfoot会话对象返回promise
- 如何从对象返回可读字符串
- 日期对象和ISO日期对象返回不同的日期
- 使用JavaScript's FormData对象返回整个html
- 节点.js请求对象 - 返回响应正文以供进一步操作
- 使用 Restangular 使用 RESTful API - RESTful API 将数组作为顶级对象返回是否安全
- 带有方法的 Javascript 对象返回“没有方法'我的方法名称'”错误
- 从 Date() 对象返回 dd-mm-yyyyy
- JSON 中的日期对象返回的数据被视为字符串
- Javascript - 如何获取字符串,打印单词,字符,空格,平均单词长度的#并作为对象返回
- 如何从新对象返回值,同时保留其方法
- 如何从对象返回某些键
- 从 Javascript 中的对象返回值