1

我在 Ember 文档中看到我可以使用类似的代码段设置绑定:

householdIncomeBinding: 'App.wife.householdIncome'

但是我想通过提供对象而不是字符串(来自全局范围的路径)来设置绑定。我需要实现类似的东西:

Ember.bind(obj1, "obj1AttributeName", obj2, "obj2AttributeName");

欢迎提出建议。谢谢!

4

2 回答 2

2

绑定只能直接连接到一个对象。fromto路径是相对于它们所连接的对象进行评估的。这些路径也可以是全局的。

查看帮助程序的文档和实现Ember.bind

/**
  Global helper method to create a new binding. Just pass the root object
  along with a `to` and `from` path to create and connect the binding.

  @method bind
  @for Ember
  @param {Object} obj The root object of the transform.
  @param {String} to The path to the 'to' side of the binding.
    Must be relative to obj.
  @param {String} from The path to the 'from' side of the binding.
    Must be relative to obj or a global path.
  @return {Ember.Binding} binding instance
*/
Ember.bind = function(obj, to, from) {
  return new Ember.Binding(to, from).connect(obj);
};

因此,您必须决定要将绑定直接连接到哪个对象,以及它如何引用另一个对象。你有几个选择:

A) 提供两个对象之间的一些关系,然后bind()用来连接相对路径:

obj1.set('friend', obj2);
Ember.bind(obj1, 'obj1AttributeName', 'friend.obj2AttributeName');

B)提供from绑定一侧的全局路径:

App.set('obj2', obj2); // make obj2 accessible from the App namespace
Ember.bind(obj1, 'obj1AttributeName', 'App.obj2.obj2AttributeName');
于 2013-05-04T18:05:10.790 回答
0

这是一个如何设置绑定的示例,我从 ember.js 网站 ( http://emberjs.com/guides/object-model/bindings/ ) 中获取了示例,并根据您的问题对其进行了定制,

App.wife = Ember.Object.create({
 householdIncome: null
});

App.husband = Ember.Object.create({
 householdIncomeBinding: 'App.wife.householdIncome'
});

App.husband.get('householdIncome'); // null

// if you now set the householdIncome to a new Ember.Object
App.husband.set('householdIncome', Ember.Object.create({amount:90000}));

// with bindings working you should be able to do this
App.wife.get('householdIncome.amount'); // 90000

希望能帮助到你

于 2013-05-04T12:12:08.370 回答