问题描述
我有多个输入框,我想根据用户的选择隐藏/取消隐藏.
I have multiple input boxes that I want to hide/unhide based on a selection from user.
我可以通过为每个输入设置一个单独的dependentObservable 并反过来让dependentObservable 观察父选择来实现这一点.
I can achieve this by having a separate dependentObservable for each input and in turn making the dependentObservable observe the parent selection.
viewModel.showField1= ko.dependentObservable(function () {
return viewModel.selectedType() ? IsFeatureVisible(viewModel, "BusinessFieldName1") : false;
}, viewModel
);
viewModel.showField1= ko.dependentObservable(function () {
return viewModel.selectedType() ? IsFeatureVisible(viewModel, "BusinessFieldName2") : false;
}, viewModel
);
这对每个领域都有些乏味.我可以使用可以带参数的dependentObservable 函数绑定元素吗?重要的是它应该在父更改时触发
this is kind of tedious to do for each field. Can I bind the elements with a dependentObservable function that can take a parameter? Important thing is it should get triggered when the parent changes
其他选项是,当父项更改时,我会遍历元素并隐藏/取消隐藏,但这需要我映射元素 ID <-> 字段的业务名称.
Other option is that when the parent changes, I loop through the elements and hide/unhide but that will require me to map the element id <-> business name of the field.
当前
<tr data-bind="visible: showField1">
<tr data-bind="visible: showField2">
需要
<tr data-bind="visible: showField('BusinessFieldName1')">
<tr data-bind="visible: showField('BusinessFieldName2')">
推荐答案
在 Knockout 中,绑定是使用dependentObservables 在内部实现的,因此您实际上可以在绑定中使用普通函数代替dependentObservable.该绑定将在一个dependentObservable 内运行您的函数,因此任何访问其值的observable 都将创建一个依赖项(您的绑定将在更改时再次触发).
In Knockout, bindings are implemented internally using dependentObservables, so you can actually use a plain function in place of a dependentObservable in your bindings. The binding will run your function inside of a dependentObservable, so any observables that have their value accessed will create a dependency (your binding will fire again when it changes).
这是一个示例:http://jsfiddle.net/rniemeyer/2pB9Y/
html
type "one", "two", or "three": <input data-bind="value: text" />
<hr />
<ul data-bind="template: { name: 'itemTmpl', foreach: items }"></ul>
js
<script id="itemTmpl" type="text/html">
<li data-bind="text: name, visible: viewModel.shouldThisBeVisible(name)"></li>
</script>
var viewModel = {
text: ko.observable("one"),
items: [{name: "one"}, {name: "two"}, {name: "three"}],
};
viewModel.shouldThisBeVisible = function(name) {
return this.text() === name;
}.bind(viewModel);
ko.applyBindings(viewModel);
这篇关于Knockoutjs:我们可以创建一个带有参数的dependentObservable 函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!