gpt4 book ai didi

ember.js - 玩 Ember.Object.reopen(),为什么我有这些结果?

转载 作者:行者123 更新时间:2023-12-04 19:14:17 28 4
gpt4 key购买 nike

我试图回答这个问题:emberjs: add routes after app initialize()

我开始尝试使用 Ember.Object.reopen(),了解它是如何工作的,或许还能找到一种方法来回答上一个问题。

感觉有点不解,不明白这段代码的行为:

jsfiddle:http://jsfiddle.net/Sly7/FpJwT/

<script type="text/x-handlebars">
<div>{{App.myObj.value}}</div>
<div>{{App.myObj2.value}}</div>
<div>{{App.myObj3.value}}</div>
</script>

App = Em.Application.create({});

App.MyObject = Em.Object.extend({value: 'initial'});

App.set('myObj', App.MyObject.create());

Em.run.later(function(){
App.get('myObj').reopen({
value: "reopenOnInstance"
}); // the template is not updated, 'initial' is still diplayed, but
console.log(App.get('myObj').get('value')); // print 'reopenOnInstance'

App.MyObject.reopen({
value: "reopenOnClass"
});
App.set('myObj2',App.MyObject.create()); // the template is updated and
console.log(App.get('myObj2').get('value')); //print 'reopenOnClass'

App.myObj3 = App.MyObject.create(); // the template is not updated but
console.log(App.myObj3.get('value')); // print 'reopenOnClass'

Em.run.later(function(){
App.get('myObj').set('value', "setWithSetter"); // the template is updated and
console.log(App.get('myObj').get('value')); // print 'setWithSetter'

App.get('myObj2').set('value', "setWithSetter"); // the template is updated and
console.log(App.get('myObj2').get('value')); // print 'setWithSetter'

App.myObj3.set('value', "setWithSetter"); // the template is not updated but
console.log(App.myObj3.get('value')); // print 'setWithSetter'

}, 2000);
},2000);

如果有人可以解释发生了什么,特别是为什么模板有时不更新,有时更新,以及调用 reopen 有什么区别?在一个类上,在一个实例上调用它。

最佳答案

不是 100% 肯定,但我会尝试回答你的问题。

首先让我们看看“myObj3”。 ember getter/setter 方法触发模板中的更新(它们触发内部事件,导致每个属性/观察者知道发生了什么)。仅手动设置一个值会更新该值,但不会触发这些事件,因此 UI 中没有任何变化。有点像当您使用可变列表时,您使用 pushObject 来确保 UI 更新。

现在让我们看看你的“重新打开”。当您重新打开该类时,它会按预期工作并更新基类。当您重新打开一个实例时,它实际上是在创建一个 mixin 并将其填充到对象的顶部。这意味着当您执行“get”时,ember 会遍历 mixin & 对象以返回值。它找到mixin并获取对象之前的值;您实际上可以在实例上用“return 'foo '+this._super()”替换该方法,您将获得 'foo initial'(想想您的对象具有像洋葱一样的层)。如果你的对象上有一组 mixin,如果你直接设置一些东西,你将很难找到正确的值(但“get”会完美地工作)。这导致您应该始终使用“set”而不是直接引用的一般规则。

旁注:您可以调用“getPath”而不是“get”,并且可以使用相对或绝对路径。例如 App.getPath('myObj2.value') 这将使代码更易于管理。也适用于“setPath”。

最后:打印最后一个值是因为您确实更改了该值(它在那里),但是 ember 更新 ui 的触发器从未触发,因为您从未在“myObj3”对象上调用 set。

编辑:在最新版本的 ember 中,实例上的重新打开看起来确实对对象进行了合并(如果该键已存在)。如果您添加新内容,mixin 只会换行。

关于ember.js - 玩 Ember.Object.reopen(),为什么我有这些结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11712435/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com