我在Ember文档中看到,我可以使用类似的代码段设置绑定:
householdIncomeBinding: 'App.wife.householdIncome'
但是我想通过提供对象而不是字符串(来自全局范围的路径)来设置绑定。 我需要达到类似的目的:
Ember.bind(obj1, "obj1AttributeName", obj2, "obj2AttributeName");
欢迎提出建议。 谢谢!
答案 0 :(得分:2)
绑定可以直接连接到一个对象。 from
和to
路径相对于它们所连接的对象进行评估。这些路径也可以是全局的。
查看Ember.bind
帮助商的docs and implementation:
/**
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');
答案 1 :(得分: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
希望有所帮助