我试图回答这个问题:emberjs: add routes after app initialize()玩Ember.Object.reopen(),为什么我有这些结果?
我开始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
有什么区别。
这一切都有道理。非常感谢你给我启迪。所以如果我理解的很好,重新打开一个像我这样做的实例,与'App.get('myObj')。value ='reopenOnInstance''有同样的行为吧? 我知道了getPath,方法,现在使用最新的ember,get具有相同的行为,您可以执行'obj.get('otherObj.someProperty')'。 – 2012-08-04 08:06:31
请参阅编辑。这意味着你是正确的,直接设置值就像重新打开实例一样。但是如果你有一些绑定到那个值的东西(比如UI),Ember会抛出一个错误,因为没有使用“set”(使用[fiddler](http://jsfiddle.net/scispear/n5B5d/)来查看错误)。 – SciSpear 2012-08-04 13:22:54
再次感谢您的编辑:)。我认为现在答案是完整的,因为我没有更多的事情要阐明。 – 2012-08-04 17:36:34