I am fairly new to knockoutJS and cannot figure out how to use the hasfocus binding to allow me to ‘click to edit’ but require a button to save.
I have set up my code (based on two of RP Niemeyer’s incredible fiddles) such that when I click a label, I get an editing input box (as expected). The problem comes in using the hasfocus binding.
This is my ‘clickToEdit’ binding (virtually identical to the second fiddle mentioned below except with the addition of accept and cancel icons):
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
});
}
};
I want the input box to become immediately focused when it becomes visible, but I do not want it to become hidden on blur. I would like to make use of a protected observable (thanks again RP) to use save/cancel on edit.
If there were an update to this fiddle: http://jsfiddle.net/rniemeyer/X9rRa/ that would focus the first field when the edit button is clicked, or an update to this fiddle: http://jsfiddle.net/rniemeyer/2jg2F/2/ where unfocusing the input box did not cause it to disappear, I could probably take it from there.
One way to do this would be to add a
focusedsub-observable to the name field, bindhasfocusagainst it, and set it to true when selecting an item.So, an item would look like:
and when selecting an item you would do:
Here is a sample: http://jsfiddle.net/rniemeyer/ks3Cj/
You could even avoid the sub-observable and just put a
hasfocus: trueon the input and it will become focused when the “edit” template is used, but I would probably be a bit more explicit about it like in the sample above.