2011-12-14 47 views
3

モデルが配列内に格納されているときに、あるモデルから別のモデルにバインドする「正しい」方法は何ですか?あなたはおそらく、あなたが「あなたの場合を除きに結合している店舗のモデルオブジェクトに配列を使用したいとは思わないでしょう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

+0

@pangratz - 配列内のどの項目でも可能です。私は主に、これがEmberによってサポートされているかどうか、もしそうなら、最良の方法に興味があります。 –

答えて

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

:一般的に私は、これはコントローラのcontent配列になりますが、簡単な例を維持することを想像しますあなたのテンプレートで{{#each}}を使ってください。

さらに例を拡張したい場合は、より多くのデザイン提案を提供することができます。

また、観測/バインディングしている配列でオブザーバー対応のpushObject()メソッドを使用することもできます。

+0

+1 for pushObject() – Egon

関連する問題