(ember.js)获取绑定属性返回undefined
问题描述:
的代码是从ember.js官方介绍:(ember.js)获取绑定属性返回undefined
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="ember-0.9.3.js"></script>
<script type="text/javascript">
var App = Ember.Application.create();
App.president = Ember.Object.create({
name: "Barack Obama"
});
App.country = Ember.Object.create({
presidentNameBinding: "App.president.name"
});
App.country.get("presidentName");
</script>
</body>
</html>
我试图显示App.country.get("presidentName");
的返回值,所以我警觉包裹,但警报始终显示undefined
。有线部分是如果我在萤火虫控制台执行此声明,它正确显示这是"Barack Obama"
。
提到的官方介绍:
注意绑定不会立即更新。灰烬等待,直到所有的 您的应用程序代码进行同步 改变
这就是为什么我不能让代码绑定属性的值的原因之前完成运行? “应用程序代码运行完成”究竟意味着什么?
答
当你玩弄具有绑定像这样的对象,你必须手动触发绑定与Ember.run.sync()
同步:
var App = Ember.Application.create();
App.president = Ember.Object.create({
name: "Barack Obama"
});
App.country = Ember.Object.create({
presidentNameBinding: "App.president.name"
});
Ember.run.sync(); // Manually sync bindings
alert(App.country.get("presidentName"));
这里有一个的jsfiddle与例如:http://jsfiddle.net/ebryn/3Ctns/
答
您需要添加一个Observer,它在初始应用程序代码运行后基本上会触发。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="js/ember-0.9.3.js"></script>
<script type="text/javascript">
var App = Ember.Application.create();
App.president = Ember.Object.create({
name: "Barack Obama"
});
App.country = Ember.Object.create({
presidentNameBinding: "App.president.name"
});
App.country.addObserver('presidentName', function() {
alert(App.country.get("presidentName"));
});
</script>
</body>
</html>
在ember.js introduction中查找'addObserver'。