javascript-如何创建自定义属性以添加if.bind?

我想创建一个属性以基于某些全局状态显示或隐藏元素.

例:

<div state='new,unknown'>yadayadayada</div>

然后,此属性将把div元素转换为有效的:

<div if.bind="['new','unknown'] | state & signal : 'state-change'">...</div>

状态值转换器会将数组转换为布尔值.

目标是如果当前全局状态是所提供的任何状态,则显示该元素,否则将其隐藏.

我不希望在其中包含自定义元素.

最佳答案
Aurelia备忘单的编号为example of naive-if custom attribute.我以此为基础制定了一个解决方案.唯一的区别是:

>计算显示或隐藏的逻辑(当然)
>也订阅全局状态,而不是仅更改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

转载注明原文:javascript-如何创建自定义属性以添加if.bind? - 代码日志