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.
, since you aren't setting the width, it won't line up well. One question: why create a hidden binding, instead of just `visible: !observable.editing`?
– Kyeotic Nov 13 '12 at 16:14