JS knockout - one way binding to persist server values?

I am currently setting up a form in Knockout in an MVC application and dumping data from a database, like this:

@Html.EditorFor(model => model.AddressPostcode) // This is filled in from the Controller.

      

This is fine as expected. However, I've worked a lot with Knockout JS and want this value to be used in my search (and thus data-bind="value: postcode"

in this postcode.

Problem? Well, when you bind to postcode: ko.observable('')

, the value of the server being filled will be replaced with '' (as you would actually expect). Is there a way to get around this?

+3


source to share


1 answer


Value binding overrides the predefined value, I think its anti-pattern is used by both MVCM on the server side and MVVM on the client side, but if you really want to use this route you need to create your own binding, for example



ko.bindingHandlers.valueWithInit = {
    init: function(element, valueAccessor, allBindingsAccessor, context) {
        var observable = valueAccessor();
        var value = element.value;

        observable(value);   

        ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor, context);
    },
    update: ko.bindingHandlers.value.update
};

      

+5


source







All Articles