簡體   English   中英

如何在Aurelia中訪問嵌套模型?

[英]How to access nested model in Aurelia?

使用Aurelia,說我有一個自定義元素<panel>和一個view / view-model InfoPanel <panel>有一個關閉按鈕,該按鈕應在InfoPanel上執行某些操作,例如,調用close()函數。

Panel.html

<template>
    <h1>${headerText}</h1>
    <button click.delegate="close()">x</button>
    <content></content>
</template>

Panel.js

@bindable({name: "headerText"})
@bindable({name: "close"})
export class Panel {
}

InfoPanel.html

<template>
    <require from="./Panel"></require>

    <panel header-text="Info" close.bind="close">
        <!-- content here -->
    </panel>
</template>

InfoPanel.js

export class InfoPanel {
    close() {
        // At this point, "this" referse to the Panel, not the InfoPanel instance.
    }
}

嘗試此操作時,出現以下錯誤:

未捕獲的錯誤:close不是函數
getFunction @ aurelia-binding.js:2033
評估@ aurelia-binding.js:1395
callSource @ aurelia-binding.js:4842
(匿名函數)@ aurelia-binding.js:4867
handleDelegatedEvent @ aurelia-binding.js:2972

我的假設是Aurelia不清楚上下文,或者我缺少了某些東西...

您嘗試做的事是可能的,但是有一些陷阱-

Panel.html

<template>
    <h1>${headerText}</h1>
    <button click.delegate="close()">x</button>
    <content></content>
</template>

要使panel.html綁定關閉,我們需要默認將其設為匿名函數。 我正在使用ES7類實例字段(類屬性的簡稱),但只要設置正確,就可以按原樣使用裝飾器作為類裝飾器-

Panel.js

export class Panel {
  @bindable headerText = '';
  @bindable close = () => {};
}

您需要使用call來傳遞一個函數引用,而不是bind它試圖計算表達式-

InfoPanel.html

<template>
    <require from="./Panel"></require>

    <panel header-text="Info" close.call="close()">
        <!-- content here -->
    </panel>
</template>

InfoPanel.js

export class InfoPanel {
    close() {
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM