添加到CollectionView的内容后,第1行出现Ember错误

Ember error at line 1 after adding to content of CollectionView

本文关键字:1行 错误 Ember CollectionView 添加      更新时间:2023-09-26

使用Ember js,我得到了一个基于树的视图结构,每个视图都有一个文本框。在任何框中输入文本并点击"回车"应为该视图添加"回复";也就是说,在原始视图下方添加另一个通过<ul>缩进的视图。

问题是,当我点击"回车"时,ember只是在ember.js脚本的第1行崩溃并出现错误。有什么想法吗?

JS Fiddle在这里:http://jsfiddle.net/TcgJB/1/

好吧,我想你的小提琴已经修好了:http://jsfiddle.net/Sly7/hVdab/

我认为主要问题是

Bap.Reply = Ember.Object.extend({
  text: null,
  children: [], // don't do that, instead declare it as null, and create
                // an empty children at instanciation time 
  addReply: function(text) {
    this.get('children').addObject(Bap.Reply.create({text:text, content: []}));
  },
});
//or an equivalent implementation, if you want each instance to be created with a default empty array:
Bap.Reply = Ember.Object.extend({
  text: null,
  children: null,
  //overriding the init method (kind of constructor for Ember's Objects
  init(): function() {
    this._super(); // very important, don't forget it
    this.set('children', []);
  },
  addReply: function(text) {
    this.get('children').addObject(Bap.Reply.create({text:text, content: []}));
  },
});

当您想要声明一个类时,如果它拥有一个子数组,则必须将其声明为null,然后在创建时将其初始化为[]。当以ember开头时,这是一个常见的问题。事实上,潜在的行为是Bap.Reply的所有实例将共享相同的子数组。

因此,当你在第一个孩子中添加一些孩子时,这可能会导致一个糟糕的结构,因为所有的孩子都有相同的父母,有些孩子和他们的兄弟姐妹有相同的孩子,等等…我认为在那之后,Ember在更新绑定和渲染视图时会丢失,所以你会遇到意想不到的奇怪错误。

顺便说一句,为了遵守Ember命名约定,我已经修复了一些小的拼写错误,因为类应该是驼色大小写的。

这里有两个有用的链接,详细介绍:

  • Ember gotchas,第6段
  • 关于命名约定