2016-05-02 33 views
3

我想創建一個屬性來顯示或隱藏基於某些全局狀態的元素。如何創建自定義屬性來添加if.bind?

實施例:

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

此屬性將接着變換div元素是有效的:

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

狀態值轉換器將所述陣列轉換成一個布爾值。

目標是如果當前全局狀態是任何提供的狀態,則顯示該元素否則將其隱藏。

我不想要一個自定義元素組成它。

回答

3

奧裏利亞小抄有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

+0

您的'GistRun'鏈接已經死亡。 – m7913d

0

您可以創建一個屬性並將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> 
+0

然後我有t o在我想要使用它的每個模型中導入我的全局狀態。所以不是我的首選方案。 –

+0

我不確定自定義屬性是否可以模擬'if.bind',因爲當它觸發時,該元素已經連接到DOM –