2011-12-14 22 views
3

當模型存儲在數組中時,從一個模型綁定到另一個模型的「正確」方式是什麼?通常,我會想象這會是一個控制器的content陣列,但爲了保持例子簡單:存儲在數組中的Ember.js綁定模型

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: ????????? 
}); 
+0

你說的 '特殊' 是什麼意思?具體含義是數組中的第一項? – pangratz 2011-12-14 23:24:39

+0

@pangratz - 確定數組中的任何項目都可以。我主要感興趣的是Ember是否支持這種方式,如果是的話,最好的方法。 – 2011-12-15 03:01:33

回答

6

您可以使用屬性來綁定該屬性。

這樣:

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

你可能不希望使用數組存儲模型對象要綁定到,除非你」重新使用模板中的{{#each}}。

如果您想進一步擴展您的示例,我可以提供更多的設計建議。此外,您還需要在您正在觀察/綁定的數組上使用觀察者感知的pushObject()方法。