knockout.js点击进行编辑,不要切换回模糊

时间:2012-10-27 23:57:52

标签: knockout.js

我对knockoutJS相当新,并且无法弄清楚如何使用hasfocus绑定来允许我“点击编辑”但需要一个按钮来保存。

我已经设置了我的代码(基于RP Niemeyer的两个令人难以置信的小提琴),这样当我点击一个标签时,我会得到一个编辑输入框(如预期的那样)。问题在于使用hasfocus绑定。

这是我的'clickToEdit'绑定(几乎与下面提到的第二小提琴相同,只是添加了accept和cancel图标):

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

            editField = document.createElement("span");
            input = document.createElement("input");
                input.setAttribute("id", "txt_" + element);
                input.setAttribute("placeholder", observable());
            acceptButton = document.createElement("i");
                acceptButton.className = "icon-ok";
                acceptButton.setAttribute("data-bind", "click: $root.acceptElementEdit");
            cancelButton = document.createElement("i");
                cancelButton.className = "icon-repeat";
                cancelButton.setAttribute("data-bind", "click: $root.cancelElementEdit");
            editField.appendChild(input);
            editField.appendChild(acceptButton);
            editField.appendChild(cancelButton);

            element.appendChild(link);
            element.appendChild(editField);

        observable.editing = ko.observable(false);
        ko.applyBindingsToNode(link, {
            text: observable,
            hidden: observable.editing,
            click: function() {
                observable.editing(true);
            }
        });

        //Apply 'editing' to the whole span
        ko.applyBindingsToNode(editField, {
            visible: observable.editing,
        });
        //Apply the value and the hasfocus bindings to the input field
        ko.applyBindingsToNode(editField.children[0], {
            value: observable,
            //hasfocus: true
        });
    }
};

我希望输入框在可见时立即聚焦,但我不希望它在模糊时隐藏。我想使用受保护的observable(再次感谢RP)在编辑时使用save / cancel。

如果对此小提琴有更新:http://jsfiddle.net/rniemeyer/X9rRa/会在单击编辑按钮时聚焦第一个字段,或者对此小提琴进行更新:http://jsfiddle.net/rniemeyer/2jg2F/2/其中未聚焦输入框未导致它消失了,我可以从那里拿走它。

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是在名称字段中添加focused子可观察对象,对其绑定hasfocus,并在选择项目时将其设置为true。

所以,一个项目看起来像:

var Item = function(name, quantity) {
    this.name = ko.protectedObservable(name);
    this.name.focused = ko.observable();
    this.quantity = ko.protectedObservable(quantity);
};

当你选择一个项目时,你会这样做:

this.editItem = function(item) {
    self.selectedItem(item);
    item.name.focused(true);
};

以下是一个示例:http://jsfiddle.net/rniemeyer/ks3Cj/

你甚至可以避免使用sub-observable并在输入上放一个hasfocus: true,当使用“edit”模板时它会聚焦,但我可能会更加明确它以上样本。