EmberJS自定义文本框视图ID-suffix

EmberJS Custom Textbox View with ID-suffix

本文关键字:视图 ID-suffix 文本 自定义 EmberJS      更新时间:2023-09-26

让我们假设我有这个Ember。ArrayController:

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"item"。我不能使用这样的字符:

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

因为句柄{{}}将值包装到ember metamorph脚本包装器和句柄{{{}}}的工作方式相同。

我想做的是自定义视图我可以这样使用:

{{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 ?

尝试以下操作。

在控制器上,只需添加:

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

然后把你的输入标签写为:

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

您应该使用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/

我最终得到了这样的解决方案:将文本框ID的计算移到Item模型。

车把:

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