剔除条件绑定(但不是本机的“if”方式)
Knockout conditional binding (but not the native "if" way)
我有一个案例看起来像这样(过于简化):
<!-- ko if: readOnly() -->
<a href="url" data-bind="click: ToggleReadOnly()" />
<!-- /ko -->
<!-- ko ifnot: readOnly() -->
<a href="url" data-bind="visible: someObservable" />
<!-- /ko -->
由于还有许多其他事情会使测试成倍增加,并重复大量代码,我需要能够在一行中完成这项工作,比如:
<a href="url" data-bind="if: readOnly() { click: ToggleReadOnly() } else: { visible: someObservable }" />
有办法做到这一点吗?
有几种方法可以实现这一点。每个人都有自己的长处和短处。但我将专注于使用模板。
为每个状态创建一个模板,无论该状态是否以只读模式呈现。您只需要在模型中添加一个函数来决定使用哪个模板。
<script type="text/html" id="template-readonly-link">
<a href="#" data-bind="click: ToggleReadOnly">ReadOnly</a>
</script>
<script type="text/html" id="template-readwrite-link">
<a href="#" data-bind="visible: someObservable">ReadWrite</a>
</script>
<!-- ko template: { name: selectTemplate } --><!-- /ko -->
function ViewModel() {
this.readOnly = ko.observable(true);
this.someObservable = ko.observable(true);
this.ToggleReadOnly = function (data, event) {
this.readOnly(!this.readOnly());
return false;
}.bind(this);
this.selectTemplate = function (data) {
return this.readOnly()
? 'template-readonly-link'
: 'template-readwrite-link';
}.bind(this);
}
小提琴
您可以探索其他方法,如自定义组件、自定义绑定等。但这可能是最容易实现的。
相关文章:
- 可以't让我的if语句处理js中的html表单输入
- 如果 a 为 false,则 if(a) === if(false)
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 为什么这在IE中的工作方式与在Firefox中不同
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- 以这种方式使用if/else-if/else是一种很好的做法
- JavaScript if语句的简洁方式
- Knockout Js 的渲染方式与基于 Json 值的 if 数据绑定不同
- 编写 if 语句的另一种方式
- 是否有一个jQuery函数来“快捷方式”if/else开关
- 我可以以某种方式在开关中使用 if 语句来添加更多案例吗?
- 剔除条件绑定(但不是本机的“if”方式)
- 如何写这段代码的最佳方式,这在javascript中有这么多的if条件
- 需要一种优雅的方式来根据输入改变一行if语句的返回结果
- 重构复杂if表达式的最佳方式
- 编写单行if语句的最佳方式
- 如何用insertAfter和insertBefore代码以三进制方式转换if块
- IF 值不会按应有的方式打开
- 更干净/更简单的jquery编写方式"if"代码
- 以正确的方式总结if-loop