【问题标题】:Why can't I set this object property?为什么我不能设置这个对象属性?
【发布时间】:2014-09-22 06:54:32
【问题描述】:

这是我的第一个 Ember.js 应用程序。我正在构建一个多项选择题(最终是一个测验)。每当单击提交按钮时,它应该将选项突出显示为绿色表示正确或红色表示不正确。我在 option.set("highlight", "green") || 上收到错误“Uncaught TypeError: undefined is not a function” option.set("highlight", "red) 在我的控制器/index.js 文件中。当我使用 console.log(option) 时,我可以看到有一个具有属性 highlight 的对象。我做错了什么?

路由/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"
        ]
      }
     ]);
   }
 });

控制器/index.js

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");
          }
        });
      });
    }
  }
});

【问题讨论】:

  • 对象选项不是 Ember 对象,因此它没有 get/set 方法。 emberjs.com/api/classes/Ember.Object.html
  • 如果您不知道您是否有余烬对象,请使用Em.set(myObject, 'name')。这将永远有效。但也许将您的对象转换为Em.Object
  • 你们会把这些作为答案而不是评论,以便他可以将其标记为正确。

标签: javascript ember.js


【解决方案1】:

object 选项不是 Ember 对象,因此它没有 get/set 方法。

正如 Krutius 所说,您可以使用 Ember.get()/Ember.set() 将属性设置为普通的旧 JavaScript 对象或 Ember 对象。示例:

Ember.set(myObject, 'property', value);
var val = Ember.get(myObject, 'property');

文档

set:http://emberjs.com/api/#method_set

get:http://emberjs.com/api/#method_get

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多