如何创建自定义属性以添加if.bind
How can I create custom attribute to add a if.bind?
我想创建一个属性来显示或隐藏基于某些全局状态的元素。
示例:
<div state='new,unknown'>yadayadayada</div>
该属性将有效地转换div元素:
<div if.bind="['new','unknown'] | state & signal : 'state-change'">...</div>
状态值转换器将数组转换为布尔值。
目标是如果当前全局状态是所提供的任何状态,则显示元素,否则隐藏它
我不想要一个包含compose的自定义元素。
Aurelia备忘单有一个naive if自定义属性的例子。我在此基础上制定了一个解决方案。唯一的区别是:
- 计算显示或隐藏的逻辑(当然)
- 也订阅全局状态,而不是仅订阅
valueChanged
代码:
import {BoundViewFactory, ViewSlot, customAttribute, templateController, inject} from 'aurelia-framework';
import {BindingEngine} from 'aurelia-binding';
import {State} from './state';
@customAttribute('naive-if')
@templateController
@inject(BoundViewFactory, ViewSlot, BindingEngine, State)
export class NaiveIf {
constructor(viewFactory, viewSlot, bindingEngine, state) {
this.show = false;
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.bindingEngine = bindingEngine;
this.state = state;
}
bind() {
this.updateView();
this.subscription = this.bindingEngine.propertyObserver(this.state, 'value')
.subscribe((newValue, oldValue) => this.updateView());
}
unbind() {
if (this.subscription) this.subscription.dispose();
}
valueChanged(newValue) {
this.updateView();
}
updateView() {
let isShowing = this.show;
let showStates = this.value.split(',');
this.show = showStates.indexOf(this.state.value) != -1;
if (this.show && !isShowing) {
let view = this.viewFactory.create();
this.viewSlot.add(view);
} else if (!this.show && isShowing) {
this.viewSlot.removeAll();
}
}
}
或者GistRun
您可以创建一个属性并将if
绑定到该属性。像这样:
import {computedFrom} from 'aurelia-framework';
export class MyViewModel {
@computedFrom('something', 'someOtherValue')
get globalState() {
//do all conditions you need
if (myArray.indexOf('something') != -1 && someOtherValue) {
return true;
}
return false;
}
}
然后你只需要绑定:
<div if.bind="globalState"></div>
相关文章:
- 正在尝试使用if和else添加类,但无法正常工作
- 在Javascript中为if/else语句添加OR
- 将 HTML 添加到 Javascript IF 函数
- XSLT在IF语句后添加图书价格
- 如何创建自定义属性以添加if.bind
- 当if条件被添加到循环中时,Javascript函数将停止工作
- 将默认选项添加到ng-if
- 从指令中向元素添加ng-if属性
- JQuery 悬停代码:添加 If 语句会破坏它
- 如何在 if else 语句期间添加暂停/延迟
- 如何添加 if 语句以循环图像
- 结构化功能.可以't在现有代码中添加if语句
- 添加 if 条件后,切换按钮停止工作
- 在if语句中添加if语句
- 如何在jQuery中添加if语句来检查JSON文件中是否存在属性
- 如何在javascript(编辑)中添加if else条件到数组中
- 添加if-else语句会导致JavaScript停止工作
- 在Javascript HTML中添加If/Else If Statment
- 向javascript添加if语句
- 如何在我的d3js示例中添加if条件