Knockout initializing empty form inputs not work after sorting sortable form elements

那年仲夏 提交于 2020-01-06 13:09:10

问题


Here is fiddle jsfiddle.net/jw7Je

I have a view model bounded to a two templates and an editable form in a single page.

The two templates are initially loaded with sample data, The form is displayed without sample data through this custom binding

ko.bindingHandlers.emptyInit = {
    init: function(element, valueAccessor, allBindingsAccessor, 
                   viewModel, bindingContext) 
    {
        element.value = '';
    }
}

<input type="text" data-bind="value: jw_fullname, valueUpdate: 'afterkeydown', emptyInit: emptyInit" placeholder="Full Name" id="jw_fullname" />

Everything loads up fine initially, but the i have sortable sections of forms through knockout sortable.

<div data-bind="sortable: data"> 
<div class="item">
       <p class="span6">
       <label>Course Name</label>
       <input type="text" data-bind="valueWithInit: jw_educname, valueUpdate: 'afterkeydown',emptyInit: jw_educname" placeholder="Course Name" class="educname" />
       </p>
       <p class="span6">
       <label>Institution Name</label>
       <input type="text" data-bind="value: jw_eduiname, valueUpdate: 'afterkeydown', emptyInit: jw_eduiname" placeholder="Insitution Name" class="eduiname" />
       </p>
  </div>
</div>

After the user make the change to the form and sorts the elements, the corresponding elements values resets to empty again, although the values in the view model are updated.

How to retain the updated values in those textboxes in sortable sections ?

I am trying with

ko.bindingHandlers.emptyInit = {
    init: function(element, valueAccessor, allBindingsAccessor, 
                   viewModel, bindingContext) 
    {

            var value = ko.utils.unwrapObservable(valueAccessor()) || '';

            if (element.value !== value) {
                element.value = value;

            }else {
                element.value = '';
            }

    },
     update: function(element, valueAccessor, allBindingsAccessor, 
                   viewModel, bindingContext) 
     {
              var value = valueAccessor();
            var valueUnwrapped = ko.unwrap(value);
            //console.log(valueUnwrapped);



     }
} 

回答1:


The fields get cleared because Knockout-sortable removes the moved elements and adds new ones in their place.

I found this pull request that seems to solve the problem: https://github.com/rniemeyer/knockout-sortable/pull/83



来源:https://stackoverflow.com/questions/21901833/knockout-initializing-empty-form-inputs-not-work-after-sorting-sortable-form-ele

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!