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

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

问题描述

假设我有像这样的基因敲除模板:

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

您将以如下方式使用它:

You would use it like:

<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/

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

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.

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

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