2014-03-24 14 views
0

讓我們假設我有這個Ember.ArrayController:EmberJS自定義文本框查看與ID後綴

App.ItemsArrayController = Ember.ArrayController.extend({ 
    //some additional functions 
}).create() 

該陣列控制器持有對象:

App.Item = Ember.Object.extend({ 
    id: 0, //after item is loaded this id contains real id of item 
    value: "some value" 
}) 

在車把模板我有:

{{#each item in App.ItemsArrayController}} 
    <input id="item" valueBinding="item.value" /> 
{{/each}} 

您可以看到,根據控制器中的項目數生成了x次輸入。與此相關的問題是所有這些輸入具有相同的「項目」ID。我不能使用類似:因爲手柄{{}}包值轉換成燼的Metamorph腳本包裝

<input id="item-{{item.id}}" valueBinding="item.value" /> 

和處理{{{}}}的工作方式相同。

我想要做的是自定義視圖,我可以用這樣的:

{{view App.TextFieldWithIdSuffix id="item-" idSuffixBinding="item.id" valueBinding="item.value"}} 

,它應該被渲染爲:

<input type="text" id="item-0" value="some text" /> 

我的觀點App.TextFieldWithIdSuffix被定義爲:

App.TextFieldWithIdSuffix = Ember.View.extend({ 
    tagName: "input" 
}); 

如何定義App.TextFieldWithIdSuffix視圖以支持xxxBindings屬性以及何時呈現id是否被後綴改變?

+1

你有沒有考慮/嘗試無論是在控制器或定製車把助手將你的ID轉換成所需的語法寫一個函數?然後你可以將你的輸入定義爲:'' – gravityplanx

+0

@gravityplanx看起來很有趣。你能指點我一些網站或提供這樣的功能的例子嗎? – petriq

+0

我會爲我提供的代碼提供答案。 – gravityplanx

回答

0

我結束了此解決方案:文本ID的計算移動到項目模型。

把手:

<input {{bind-attr id="item.textboxId"}} 
     type="text" {{bind-attr value="item.value"}} /> 

恩貝爾模型:

App.Item = Ember.Object.extend({ 
    id: 0, //after item is loaded this id contains real id of item 
    value: "some value", 
    textboxId: function() { 
     return "item-" + this.get("id"); 
    }.property("id") 
}); 
1

請嘗試以下操作。

在您的控制器,只需添加:

idFormat: function(id) { 
    return "item-" + id; 
} 

,然後寫輸入標籤爲:

<input id={{idFormat item.id}} valueBinding"item.value" /> 
0

你應該使用bind-ATTR幫手

http://emberjs.com/guides/templates/binding-element-attributes/

把手

<input type="text" {{bind-attr id="idFormat" }} value="some text" />

控制器

idFormat: function(id) { return "item-" + id; }

哦,還同時上述解決您的眼前問題,你可能想使用這取決於你在做什麼輸入傭工。

http://emberjs.com/guides/templates/input-helpers/

+0

控制器如何獲取id參數? – petriq

+1

通常它來自將在ControllerNameRouter類中設置的模型。我上面的示例稍微不完整 - 我可能會使用property(「id」)來監視它,而不是像傳入解決方案那樣傳入 - 我只是在控制器中執行操作,而不是在模型中執行。 – stephenmichm