Javascript 为什么可以';我不能设置这个对象属性吗?
这是我的第一个Ember.js应用程序。我正在设计一个选择题(最终是一个测验)。无论何时单击submit按钮,都应突出显示选项,绿色表示正确,红色表示不正确。我在controllers/index.js文件中的option.set(“highlight”,“green”)| | option.set(“highlight”,“red”)上得到错误“uncaughttypeerror:undefined不是函数”。当我console.log(option)时,我可以看到有一个具有highlight属性的对象。我做错了什么 routes/index.jsJavascript 为什么可以';我不能设置这个对象属性吗?,javascript,ember.js,Javascript,Ember.js,这是我的第一个Ember.js应用程序。我正在设计一个选择题(最终是一个测验)。无论何时单击submit按钮,都应突出显示选项,绿色表示正确,红色表示不正确。我在controllers/index.js文件中的option.set(“highlight”,“green”)| | option.set(“highlight”,“red”)上得到错误“uncaughttypeerror:undefined不是函数”。当我console.log(option)时,我可以看到有一个具有highlight
var IndexRoute = Ember.Route.extend({
model: function() {
return Ember.A([
{
question: "What's up?",
answer: 'option b',
options: [
{
text: "option a",
active: false,
highlight: ''
},
{
text: "option b",
active: false,
highlight: '1'
}
]
},
{
question: "How many?",
answer: 'two',
options: [
"one",
"two"
]
}
]);
}
});
var IndexController = Ember.ObjectController.extend({
actions:{
submitAction : function(){
this.get('model').forEach(function (item){
item.options.forEach(function (option) {
if (option.text === item.answer) {
console.log(option);
option.set("highlight", "green");
console.log(option.highlight);
}
if (option.active && (option.text !== item.answer)) {
option.set("highlight", "red");
}
});
});
}
}
});
控制器/index.js
var IndexRoute = Ember.Route.extend({
model: function() {
return Ember.A([
{
question: "What's up?",
answer: 'option b',
options: [
{
text: "option a",
active: false,
highlight: ''
},
{
text: "option b",
active: false,
highlight: '1'
}
]
},
{
question: "How many?",
answer: 'two',
options: [
"one",
"two"
]
}
]);
}
});
var IndexController = Ember.ObjectController.extend({
actions:{
submitAction : function(){
this.get('model').forEach(function (item){
item.options.forEach(function (option) {
if (option.text === item.answer) {
console.log(option);
option.set("highlight", "green");
console.log(option.highlight);
}
if (option.active && (option.text !== item.answer)) {
option.set("highlight", "red");
}
});
});
}
}
});
对象选项不是余烬对象,因此它没有
get
/set
方法
正如Krutius所说,您可以使用Ember.get()
/Ember.set()
来设置普通旧JavaScript对象或Ember对象的属性。例如:
Ember.set(myObject, 'property', value);
var val = Ember.get(myObject, 'property');
文档
设置
:
get
:对象选项不是余烬对象,因此它没有get/set方法。如果您不知道是否有余烬对象,请使用Em.set(myObject,'name'))
。这总是有效的。但也许可以将您的对象转换为Em.Object
?你们能把这些作为答案而不是注释,这样他就可以把它标记为正确的吗。