Knockout Inline Edit Binding

五迷三道 提交于 2019-11-28 09:30:41

Just as an alternative: the code that I have used for inline editing looks like:

ko.bindingHandlers.hidden = {
    update: function(element, valueAccessor) {
        ko.bindingHandlers.visible.update(element, function() { return !ko.utils.unwrapObservable(valueAccessor()); });
    }        
};

ko.bindingHandlers.clickToEdit = {
    init: function(element, valueAccessor) {
        var observable = valueAccessor(),
            link = document.createElement("a"),
            input = document.createElement("input");

        element.appendChild(link);
        element.appendChild(input);

        observable.editing = ko.observable(false);

        ko.applyBindingsToNode(link, {
            text: observable,
            hidden: observable.editing,
            click: observable.editing.bind(null, true)
        });

        ko.applyBindingsToNode(input, {
            value: observable,
            visible: observable.editing,
            hasfocus: observable.editing
        });
    }
};

http://jsfiddle.net/rniemeyer/Rg8DM/

Here is my inline edit binding (fiddle), it relies on jQuery for some DOM manipulation though.

HTML:

<p>
    Set an alarm for <span data-bind="inline: startTime"></span>
    using <span data-bind="inline: snoozeCount"></span> Snooze(s).
</p>

JS:

ko.bindingHandlers.inline= {
    init: function(element, valueAccessor) {
        var span = $(element);
        var input = $('<input />',{'type': 'text', 'style' : 'display:none'});
        span.after(input);

        ko.applyBindingsToNode(input.get(0), { value: valueAccessor()});
        ko.applyBindingsToNode(span.get(0), { text: valueAccessor()});

        span.click(function(){
            input.width(span.width());
            span.hide();
            input.show();
            input.focus();
        });

        input.blur(function() { 
            span.show();
            input.hide();
        });

        input.keypress(function(e){
            if(e.keyCode == 13){
               span.show();
               input.hide();
           }; 
        });
    }
};

The width is set in the click function because of the unreliability of the width on Dom Ready: it was coming out as 0 half the time.

I also made one for toggles (boolean) that you just click to switch:

ko.bindingHandlers.inlineToggle = {
    init: function(element, valueAccessor, allBindingsAccessor) {

        var displayType = allBindingsAccessor().type || "bool";
        var displayArray = [];

        if (displayType == "bool") {
            displayArray = ["True", "False"];
        } else if (displayType == "on") {
            displayArray = ["On", "Off"];
        } else {
           displayArray = displayType.split("/");
        } 

        var target = valueAccessor();  
        var observable = valueAccessor()
        var interceptor = ko.computed(function() {
            return observable() ? displayArray[0] : displayArray[1];
        });

        ko.applyBindingsToNode(element, { text: interceptor });
        ko.applyBindingsToNode(element, { click: function(){ target (!target())} });
    }
};

Apply like so (second param is optional):

<span data-bind="inlineToggle: alert, type: 'on'"></span>

The fiddle also contains one for select and multi-select, but right now the multi-select causes the display to jump. I'll need to fix that.

Even though the answer is already accepted I believe I found a better solution so I would like to share it.

I ended up using what was in the documentation here http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.html#example-supplying-additional-values-to-descendant-bindings

and came up with this rough draft of the binding:

ko.bindingHandlers['textinlineeditor'] = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

        var observable = valueAccessor();
        var value = ko.utils.unwrapObservable(observable);

        var saveHandler = allBindingsAccessor().editorsavehandler || function (newValue) { observable(newValue); return true; };
        var inputType = allBindingsAccessor().editorinputtype || "text";            

        var vm = new inlineEditorViewModel({ val: value, saveHandler: saveHandler });

        $(element).append("<span data-bind=\"text: editableValue, hidden: editing\"></span>");
        $(element).append("<input type=\"" + inputType + "\" data-bind=\"value: editableValue, visible:editing\"/>");
        $(element).append("<div class=\"pull-right\"></div>");
        $(element).find("div.pull-right").append("<span class=\"glyphicon glyphicon-edit\" aria-hidden=\"true\" data-bind=\"click: edit, hidden: editing\"></span>");
        $(element).find("div.pull-right").append("<span class=\"glyphicon glyphicon-check\" aria-hidden=\"true\" data-bind=\"click: save, visible:editing\"></span>");
        $(element).find("div.pull-right").append("<span class=\"glyphicon glyphicon-remove-circle\" aria-hidden=\"true\" data-bind=\"click: cancelSave, visible:editing\"></span>");

        var innerBindingContext = bindingContext.extend(vm);
        ko.applyBindingsToDescendants(innerBindingContext, element);

        return { controlsDescendantBindings: true };
    }
};

the model I used in the code is

var inlineEditorViewModel = function (init) {
    var self = this;

    self.editableValue = ko.observable(init.val);
    self.lastEditableValue = ko.observable(init.val);

    self.editing = ko.observable(false);

    self.edit = function () {
        self.editing(true);
    };

    self.save = function () {
        if (init.saveHandler(self.editableValue())) {
            self.lastEditableValue(self.editableValue());
            self.editing(false);
        }
    };

    self.cancelSave = function () {
        self.editableValue(self.lastEditableValue());
        self.editing(false);
    };
};

in your html you would use it like

<div data-bind="textinlineeditor: name, editorsavehandler: saveName"></div>

Note: I am using Bootstrap so that is where the icons in the binding html are from.

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