我有一个具有一些属性的基类。我将这个类继承到另外两个 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
有两种方法可以避免共享行为。
- 使用计算属性
- 像我一样初始化
init
函数
主题中的更多引用 here正如@lock所说
关于javascript - Controller 父级在其子级之间共享内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41387255/