课程表

Ember.js 基础

Ember.js 对象模型

Ember.js handlebars模板

Ember.js 路由

Ember.js 组件

Ember.js 控制器

Ember.js 模型

Ember.js 测试

工具箱
速查手册

Ember 数据绑定

当前位置:免费教程 » JS/JS库/框架 » Ember.js

正如其他的框架一样,Ember也有它特有的数据绑定方式,并且可以在任何一个对象上使用绑定。而然,数据绑定大多数情况都是使用在Ember框架本身,对于开发者最好还是使用计算属性更为简单方便。

双向绑定

  1. // 双向绑定
  2. Wife = Ember.Object.extend({
  3. householdIncome: 800
  4. });
  5. var wife = Wife.create();
  6.  
  7. Hasband = Ember.Object.extend({
  8. // 使用 alias方法实现绑定
  9. householdIncome: Ember.computed.alias('wife.householdIncome')
  10. });
  11.  
  12. hasband = Hasband.create({
  13. wife: wife
  14. });
  15.  
  16. console.log('householdIncome = ' + hasband.get('householdIncome')); // output > 800
  17. // 可以双向设置值
  18.  
  19. // 在wife方设置值
  20. wife.set('householdIncome', 1000);
  21. console.log('householdIncome = ' + hasband.get('householdIncome')); // output > 1000
  22. // 在hasband方设置值
  23. hasband.set('householdIncome', 10);
  24. console.log('wife householdIncome = ' + wife.get('householdIncome'));

run result

需要注意的是绑定并不会立刻更新对应的值,Ember会等待直到程序代码完成运行完成并且是在同步改变之前,所以你可以多次改变计算属性的值。由于绑定是很短暂的所以也不需要担心开销问题。

单向绑定

单向绑定只会在一个方向上传播变化。相对双向绑定来说,单向绑定做了性能优化,对于双向绑定来说如果你只是在一个方向上设置关联其实就是一个单向绑定。

  1. var user = Ember.Object.create({
  2. fullName: 'Kara Gates'
  3. });
  4.  
  5. UserComponent = Ember.Component.extend({
  6. userName: Ember.computed.oneWay('user.fullName')
  7. });
  8.  
  9. userComponent = UserComponent.create({
  10. user: user
  11. });
  12.  
  13. console.log('fullName = ' + user.get('fullName'));
  14. // 从user可以设置
  15. user.set('fullName', "krang Gates");
  16. console.log('component>> ' + userComponent.get('userName'));
  17. // UserComponent 设置值,user并不能获取,因为是单向的绑定
  18. userComponent.set('fullName', "ubuntuvim");
  19. console.log('user >>> ' + user.get('fullName'));

run result

关于数据绑定的知识点不多,相对来说不是重点,毕竟对象之间的关联关系是越少、越简单越好。关联关系多了反而难以维护。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号