Problem
I have created a custom binding that replaces html br occurences in an observable with \r\n in order to be displayed in a textarea. This works OK for the initial display of the value, but furthers changes to the displayed text don't trigger the update function of the custom binding.
Code
ko.bindingHandlers.Br2Nl = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var observable = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(observable);
var transformed = Br2Nl(valueUnwrapped);
$(element).val(transformed);
}
};
function Br2Nl(content)
{
var response = new String(content);
return response.replace(/<br \/>/g, "\r\n");
}
My initial assumption was that the problem was that I didn't actually trigger the update of the underlying observable so I modified the update function to do so, but with no success:
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var observable = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(observable);
var transformed = Br2Nl(valueUnwrapped);
//update observable with transformed value
observable(transformed);
$(element).val(transformed);
}
Is there a proper way to update/filter the value of an observable using a custom binding?
Custom binding usage:
<textarea data-bind="Br2Nl: PropertyName" rows="5"> </textarea>
This is the fiddle for it: http://jsfiddle.net/bWHBU/
As it can be observed, nothing happens to the observable(div below) when the content of the textarea changes. However, when the 'Br2Nl' custom binding is replaced with the 'value' binding, the observable is updated.
Final solution here: http://jsfiddle.net/bWHBU/5/
Replaced 'keyup' with 'change' event to avoid vertical scrollbar repositioning issue on Firefox.