Knockout js -> Bind to editable div text?

萝らか妹 提交于 2019-12-18 05:40:15

问题


How can I bind an observable to an editable div text content?


回答1:


You will need to modify the default "text" binding so that it is able to write the content of the edited div back to the observable. A simple custom binding handler for this task can look like this:

ko.bindingHandlers.editableText = {
    init: function(element, valueAccessor) {
        $(element).on('blur', function() {
            var observable = valueAccessor();
            observable( $(this).text() );
        });
    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).text(value);
    }
};

But please note that this example code requires jQuery.

Usage is as simple as this:

<div contentEditable="true" data-bind="editableText: foo"></div>

Here is an example (written in CoffeeScript): http://jsfiddle.net/aBUEu/1/




回答2:


You can't do that by default, because changing text in editable div won't raise any event that would update the value in your model.

You will need a custom binding for this. You can read about it here: http://knockoutjs.com/documentation/custom-bindings.html



来源:https://stackoverflow.com/questions/11448367/knockout-js-bind-to-editable-div-text

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