从 HTML 标记中为 observable 赋予初始值 [英] Giving initial value to observable from the HTML markup
问题描述
我正在尝试创建一个将一些 HTML 输出到视图的 HtmlHelper
扩展.在这个 HTML 中,我连接了一些 KnockoutJS 绑定.我是 KO 的新手,所以我仍在努力完成一些事情.无论如何,我想要做的是生成绑定到我的客户端代码上的 observables 的输入字段(在服务器端代码中),然后通过隐藏字段的值设置 observables 的初始值.不幸的是,这对我不起作用.所以我想知道是否有任何方法可以完成这项工作(即使我必须完全不同).
I'm trying to create an HtmlHelper
extension that outputs some HTML to the view. In this HTML I'm wiring up some KnockoutJS binding. I'm new to KO so I'm still struggling in getting some things done. Anyway, what I'm trying to do is generate input fields (in the server-side code) bound to observables on my client-side code, then set the initial values of the observables through the value of the hidden fields. Unfortunately, that is not working for me. So I'm wondering if there any way I could get this done (even if I have to do it completely different).
这就是我的主要工作:
在我的客户端视图模型中,我有以下内容:
In my client side view model I have the following:
self.dataSource = ko.observable();
self.pageSize = ko.observable();
我的扩展方法输出如下:
And my extension method outputs the following:
<input type="hidden" value="/Employee/Get" data-bind="value: dataSource" />
<input type="hidden" value="30" data-bind="value: pageSize" />
但是当页面呈现时,当我检查元素时,我注意到输入字段的 value
被设置为一个空字符串,我相信这是因为 observables 的声明方式.但是有没有办法覆盖这种行为或其他什么?
But when the page renders, when I inspect the elements I notice that the value
of the input fields is being set to an empty string, which I believe is because of the way observables are being declared. But is there a way to override this behavior or something?
推荐答案
可以用来使代码更简洁的一种替代方法是使用自定义绑定,该绑定通过使用元素的当前值对其进行初始化来包装值绑定.
One alternative you can use to keep your code a bit cleaner is to use a custom binding that wraps the value binding by initializing it with the element's current value.
你甚至可以让它在你的视图模型上创建 observables,如果它们不存在的话.
You can even have it create observables on your view model, if they don't exist.
绑定可能类似于:
ko.bindingHandlers.valueWithInit = {
init: function(element, valueAccessor, allBindingsAccessor, data) {
var property = valueAccessor(),
value = element.value;
//create the observable, if it doesn't exist
if (!ko.isWriteableObservable(data[property])) {
data[property] = ko.observable();
}
data[property](value);
ko.applyBindingsToNode(element, { value: data[property] });
}
};
你会像这样使用它:
<input value="someValue" data-bind="valueWithInit: 'firstName'" />
请注意,属性名称在引号中,这允许绑定创建它,如果它不存在而不是从未定义的值中出错.
Note that the property name is in quotes, this allows the binding to create it, if it does not exist rather than error out from an undefined value.
这是一个示例:http://jsfiddle.net/rniemeyer/BnDh6
这篇关于从 HTML 标记中为 observable 赋予初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!