如何扩展淘汰赛 observables 以从绑定中读取默认值? [英] 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 代码完全不知道剃刀世界,我想避免草率:
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.
推荐答案
您可以尝试创建自己的自定义绑定处理程序来实现此目的:
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"/>
这篇关于如何扩展淘汰赛 observables 以从绑定中读取默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!