簡體   English   中英

Ember.js綁定模型存儲在一個數組中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM