Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

knockout.js - How to extend knockout observables to read default value from binding?

I have finally found the time to start learning KnockoutJS while building a new MVC4 application. I am trying to figure out the best way to initialize an observable value from a default value that is already set in the view.

This is a contrived example, but I would like to render out a default value for an observable directly to the view as follows:

<input type="hidden" 
       value="@Model.SomeValue"
       data-bind="value: myObservableReference"/>

I know that a default value is normally initialized via:

model.myObservableReference = ko.obervable("SomeValue");

However, I would like to find a way to extend the initialization such that:

model.myObservableReference = ko.obervable();

would read the existing value from the binding if a value exists.

As I have so far managed to keep my KnockoutJS code completely unaware of the razor world, I want to to avoid the sloppiness of:

model.myObservableReference = ko.obervable(@Model.SomeValue);

I am guessing this would be handled via either an extender or custom binder, but if someone could point me in the right direction it would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try creating your own custom binding handler to achieve this:

ko.bindingHandlers.initializeValue = {
    init: function(element, valueAccessor) {
        valueAccessor()(element.getAttribute('value'));
    },
    update: function(element, valueAccessor) {
        var value = valueAccessor();
        element.setAttribute('value', ko.utils.unwrapObservable(value))
    }
};

<input type="hidden" value="@Model.SomeValue"
       data-bind="initializeValue:myObservableReference, value: myObservableReference"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...