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

Javascript 如何创建自定义属性以添加if.bind?,javascript,attributes,aurelia,Javascript,Attributes,Aurelia,我想创建一个属性来显示或隐藏基于某些全局状态的元素 例如: <div state='new,unknown'>yadayadayada</div> yadayada 然后,该属性将div元素转换为: <div if.bind="['new','unknown'] | state & signal : 'state-change'">...</div> 。。。 状态值转换器将数组转换为布尔值 目标是,如果当前全局状态是提供的任何状态,

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

例如:

<div state='new,unknown'>yadayadayada</div>
yadayada
然后,该属性将div元素转换为:

<div if.bind="['new','unknown'] | state & signal : 'state-change'">...</div>
。。。
状态值转换器将数组转换为布尔值

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


我不想要包含compose的自定义元素。

您可以创建一个属性,并将
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>

Aurelia备忘单上有。我根据它构思了一个解决方案。唯一的区别是:

  • 计算显示或隐藏的逻辑(当然)
  • 也订阅全局状态,而不仅仅是
    valueChanged
代码:


或者

然后我必须在我想要使用全局状态的每个模型中导入全局状态。因此,这不是我的首选解决方案。我不确定自定义属性是否可以模拟
if.bind
,因为当它触发时,元素已经附加到DOMYour
GistRun
链接已失效。
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();
    }
  }
}