Knockout content editable custom binding

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

Why in this example http://jsfiddle.net/JksKx/8/ div lost cursor when i write text? How to fix such behavior?

回答1:

The keyup event is firing and writing to your viewmodel, which then triggers the update function of the custom binding. This is writing the innerHTML back to the element, which is causing you to lose focus.

An easy fix is to check in the update function if the element.innerHTML already is the same as the value that you want to set it to.

http://jsfiddle.net/rniemeyer/JksKx/9/

ko.bindingHandlers.htmlValue = {     init: function(element, valueAccessor, allBindingsAccessor) {         ko.utils.registerEventHandler(element, "keydown", function() {             var modelValue = valueAccessor();             var elementValue = element.innerHTML;             if (ko.isWriteableObservable(modelValue)) {                 modelValue(elementValue);             }             else { //handle non-observable one-way binding                 var allBindings = allBindingsAccessor();                 if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers'].htmlValue) allBindings['_ko_property_writers'].htmlValue(elementValue);             }         }                                      )     },     update: function(element, valueAccessor) {         var value = ko.utils.unwrapObservable(valueAccessor()) || "";         if (element.innerHTML !== value) {             element.innerHTML = value;         }     } }; 


回答2:

might want to change keydown to keyup, but other than that works really well =)

ko.utils.registerEventHandler(element, "keyup", function() { 


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