Knockout JS “uniqueName” binding - Same name to two fields

前端 未结 4 1031
遇见更好的自我
遇见更好的自我 2021-01-14 09:31

I am using Knockout JS to create an editor. I am using the foreach property to loop around a list in my model.

 

        
4条回答
  •  不知归路
    2021-01-14 10:08

    The uniqueName binding just increments an index and sets the name (with a fix for IE).

    It looks like:

    ko.bindingHandlers['uniqueName'] = {
        'init': function (element, valueAccessor) {
            if (valueAccessor()) {
                element.name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
    
                // Workaround IE 6/7 issue
                // - https://github.com/SteveSanderson/knockout/issues/197
                // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
                if (ko.utils.isIe6 || ko.utils.isIe7)
                    element.mergeAttributes(document.createElement(""), false);
            }
        }
    };
    

    So, you can create a custom binding that uses the last index and sets the appropriate attribute

    ko.bindingHandlers.valmsg = {
        init: function(element) {
            element.setAttribute("data-valmsg-for", "ko_unique_" + ko.bindingHandlers.uniqueName.currentIndex);
        }
    };
    

    Now, you would just use it like:

    
        
             
        
    
    
         
    
    

提交回复
热议问题