本文介绍了Knockout.js:我们可以创建带参数的dependentObservable函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个输入框,要根据用户的选择隐藏/取消隐藏.

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内部运行您的函数,因此访问其值的任何可观察对象将创建一个依赖项(您的绑定在更改时将再次触发).

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);

这篇关于Knockout.js:我们可以创建带参数的dependentObservable函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 18:24