javascript - Controller 父级在其子级之间共享内容

标签 javascript ember.js

我有一个具有一些属性的基类。我将这个类继承到另外两个 Controller 中。不过,每当我为此变量设置内容时,该内容就会在两个 Controller 之间共享。我不希望这种情况发生,否则我会使用 Mixins。我想将一个 child 的内容设置为某些内容,当我转到另一条路线时,内容仍然是空白。

// base controller
export default Ember.Controller.extend({
    method: null,
    actions: {
        changeMethod() {
            this.set('method', 'content is shared');
        }
    }
}
// children.js
import BaseClass from './base-class';

export default BaseClass.extend({ //code here });

// child1.hbs
{{method}} - it shows the same as child2.hbs

// child2.hbs
{{method}} - it shows the same as child1.hbs

最佳答案

好吧,我要做的与他们为 Mixins 推荐的相同:我创建了一个 init() 方法,将变量设置为默认值。在我给出的示例中,它变成了:

export default Ember.Controller.extend({
    method: null,
    init() {
        this._super():
        this.set('method', null);
    },
    actions: {
        changeMethod() {
            this.set('method', 'content is shared');
        }
    }
}

创建的对象共享相同的原型(prototype)。根据 Mozilla 的说法:

Changes to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior.

更多关于这个主题的内容可以参见here

有两种方法可以避免共享行为。

  1. 使用计算属性
  2. 像我一样初始化 init 函数

主题中的更多引用 here正如@lock所说

关于javascript - Controller 父级在其子级之间共享内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41387255/

相关文章:

javascript - 如何使用 pdo 将录制的音频文件上传到网站文件夹

javascript - 解析 JSON 文件 - 子数组或方括号内的 node.js

javascript - Grunt usemin : concatenated JavaScript file not replaced in index. html 文件

ember.js - EmberJS,如何观察哈希的任何对象的变化

javascript - Ember.js ArrayController 错误

javascript - 为 Google map 信息框创建自定义关闭按钮

javascript - d3 - 向路径添加标记

ember.js - 查找操作(AJAX 请求)被拒绝,未在线路中看到

node.js - npm install without symlinks 选项不起作用

ember.js - 使用关闭操作,除非你需要冒泡