Knockout.js 模板中的唯一 ID [英] Unique ids in knockout.js templates

查看:16
本文介绍了Knockout.js 模板中的唯一 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的 Knockout.js 模板:

Suppose I have knockout.js template like this:

<script type="text/html" id="mytemplate">
    <label for="inputId">Label for input</label>
    <input type="text" id="inputId" data-bind="value: inputValue"/>
</script>

如果我在页面上的多个位置呈现此模板,我最终会得到多个具有相同 id 的输入(以及多个具有相同 for 值的标签),这会产生不良后果.特别是,所有依赖于 id 的代码可能无法正常工作(在我的情况下,我使用 jquery.infieldlabel 插件,该插件被具有相同 id 的多个输入混淆).我现在解决这个问题的方法是向绑定到模板的模型添加唯一的 id 属性:

If I render this template in several places on the page I end up with several inputs with the same id (and several labels with the same for value), which has bad consequences. In particular, all code that depends on ids may not work properly (in my case I use jquery.infieldlabel plugin that gets confused by multiple inputs with the same id). The way I solve this issue now is I add unique id attribute to the model that I bind to the template:

<script type="text/html" id="mytemplate">
    <label data-bind="attr: {for: id}>Label for input</label>
    <input type="text" data-bind="attr: {id: id}, value: inputValue"/>
</script>

这有效,但它不是很优雅,因为我必须在我的模型中使用这个不用于其他任何东西的人工 id 属性.我想知道这里是否有更好的解决方案.

This works, but it's not very elegant since I have to have this artificial id attribute in my models that is not used for anything else. I wonder if there is a better solution here.

推荐答案

另一种不依赖字段绑定顺序的替代方法是让绑定在数据上设置 id 属性本身,这需要是一个可观察的.

An alternative that does not rely on the order that the fields are bound is to have the binding set an id property on the data itself, which would need to be an observable.

ko.bindingHandlers.uniqueId = {
    init: function(element, valueAccessor) {
        var value = valueAccessor();
        value.id = value.id || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);

        element.id = value.id;
    },
    counter: 0,
    prefix: "unique"
};

ko.bindingHandlers.uniqueFor = {
    init: function(element, valueAccessor) {
        var value = valueAccessor();
        value.id = value.id || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);

        element.setAttribute("for", value.id);
    } 
};

你会像这样使用它:

<ul data-bind="foreach: items">
    <li>
        <label data-bind="uniqueFor: name">Before</label>
        <input data-bind="uniqueId: name, value: name" />
        <label data-bind="uniqueFor: name">After</label>
    </li>
</ul>

示例:http://jsfiddle.net/rniemeyer/JjBhY/

向 observable 函数添加属性的好处在于,当您将其转换为 JSON 发送回服务器时,它会自然消失,因为 observable 将变成其未包装的值.

The nice thing about adding a property to the observable function is that when you turn it into JSON to send back to the server, then it will just naturally disappear as the observable will just turn into its unwrapped value.

这篇关于Knockout.js 模板中的唯一 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆