[英]Ember.js binding models stored within an array
当模型存储在数组中时,从一个模型绑定到另一个模型的“正确”方法是什么? 通常我会想象这将是一个Controller的content
数组,但为了保持示例简单:
MyApp.websites = [];
MyApp.websites.push(Ember.Object.create({
name: "Stackoverflow"
}));
MyApp.websites.push(Ember.Object.create({
name: "Serverfault"
}));
MyApp.favorite = Ember.Object.create({
// how should this be bound to a specific element of MyApp.websites?
nameBinding: ?????????
});
您可以使用属性来绑定它。
这条路:
MyApp.websites = [];
MyApp.websites.push(Ember.Object.create({
name: "Stackoverflow"
}));
MyApp.websites.push(Ember.Object.create({
name: "Serverfault"
}));
MyApp.mainController = Ember.Object.create({
currentWebsiteIndex: 0,
currentWebsite: function() {
return MyApp.websites[this.get("currentWebsiteIndex")];
}.property("currentWebsiteIndex")
});
MyApp.favorite = Ember.Object.create({
// how should this be bound to a specific element of MyApp.websites?
nameBinding: "MyApp.mainController.currentWebsite.name"
});
这只是为了证明这个想法,更好的实现方式是:
MyApp.websites = Ember.ArrayProxy.create({
content: [],
currentWebsiteIndex: 0,
currentWebsite: function() {
return this.objectAt(this.get("currentWebsiteIndex"));
}.property("currentWebsiteIndex")
});
MyApp.websites.pushObject(Ember.Object.create({
name: "Stackoverflow"
}));
MyApp.websites.pushObject(Ember.Object.create({
name: "Serverfault"
}));
MyApp.favorite = Ember.Object.create({
// how should this be bound to a specific element of MyApp.websites?
nameBinding: "MyApp.websites.currentWebsite.name"
});
除非您在模板中使用{{#each}},否则您可能不希望使用数组来存储要绑定的模型对象。
如果你想进一步扩展你的例子,我可以提供更多的设计建议。
此外,您将需要在正在观察/绑定的数组上使用观察者感知的pushObject()方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.