简体   繁体   English

Ember.js绑定模型存储在一个数组中

[英]Ember.js binding models stored within an array

What is the 'correct' way to bind from one model to another when the models are stored within an array? 当模型存储在数组中时,从一个模型绑定到另一个模型的“正确”方法是什么? Typically I'd imagine that this would be a Controller's content array, but to keep the example simple: 通常我会想象这将是一个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: ?????????
});

You can use a property to bind that. 您可以使用属性来绑定它。

This way: 这条路:

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"
});

This is just to demonstrate the idea, a better implementation would be: 这只是为了证明这个想法,更好的实现方式是:

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"
});

You probably wouldn't want to use an array to store model objects you're binding to unless you're using {{#each}} in your template. 除非您在模板中使用{{#each}},否则您可能不希望使用数组来存储要绑定的模型对象。

If you wanted to expand your example a bit further, I could provide more design suggestions. 如果你想进一步扩展你的例子,我可以提供更多的设计建议。

Also, you'll want to use the observer-aware pushObject() method on Arrays that you're observing/binding to. 此外,您将需要在正在观察/绑定的数组上使用观察者感知的pushObject()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM