如何延长淘汰赛观测从结合阅读默认值? [英] How to extend knockout observables to read default value from binding?
问题描述
我终于找到的时候开始学习KnockoutJS同时建立一个新的应用程序MVC4。我试图找出初始化从已经在视图中设置默认值的可观测值的最佳方式。
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.
由于我迄今设法使我的KnockoutJS code完全不知道剃须刀的世界,我想避免的草率:
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);
我猜测这将通过要么是延长或定制绑定来处理,但是如果有人能在正确的方向点我将不胜AP preciated。
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.
推荐答案
您可以尝试创建自己的自定义绑定处理程序来实现这一点:
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"/>
这篇关于如何延长淘汰赛观测从结合阅读默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!