Knockout内容可编辑自定义绑定 [英] Knockout content editable custom binding

查看:120
本文介绍了Knockout内容可编辑自定义绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在这个例子中 http://jsfiddle.net/JksKx/8/ div在我写文字时丢失了光标?如何修复这种行为?

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

推荐答案

keyup事件触发并写入你的viewmodel,然后触发更新功能自定义绑定。这是将innerHTML写回元素,这会导致你失去焦点。

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.

如果element.innerHTML已经是,那么检查更新函数是一个简单的方法。与您想要设置的值相同。

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

这篇关于Knockout内容可编辑自定义绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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