2016-12-30 74 views
6

我使用Aurelia的自定義元素重複一組條目。這裏是示例要點:https://gist.run/?id=38aee854447122f021bc05e1e0de25aeAurelia自定義元素:訪問父級方法

現在,我需要訪問deleteEntry(entry)方法時點擊自定義元素中定義的按鈕。我嘗試使用$parent.deleteEntry(entry),但它不工作。

看到this問題,但它已超過一年,我想知道是否有一個更清潔的方式來實現這一點。

+1

夫婦可能有用的帖子[這裏](http://stackoverflow.com/questions/36813465/passing-the-parent-when-parent-is-the-same-component-type-in​​-aurelia/36875154 #36875154)和[here](http://stackoverflow.com/questions/32777303/custom-elements-binding-context-what-is-it-exactly-how-to-access-parent-vm/32781324#32781324) –

回答

9

代碼爲什麼不使用call結合來完成呢?

下面是一個例子:https://gist.run?id=3cc553ea3bd7ed1862d87d8dbe4f5f84

app.html

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

     <h2 class='text-center'>Journal Entries</h2> 

     <div> 
      <entry repeat.for='entry of entries' entry.bind='entry' delete-function.call="deleteEntry(entry)"></entry> 
     </div> 

</template> 

app.js

export class App { 

    entries = [{ 
      'date': 'Jan 1', 
      'note': 'Hello World' 
     }, { 
      'date': 'Jan 2', 
      'note': 'Good Morning' 
     }]; 


    deleteEntry(entry) { 
     console.log("Deleting entry"); 
     console.log(entry); 

     const index = this.entries.indexOf(entry); 

     this.entries.splice(index, 1); 
    } 
} 

entry.html

<template> 
    <div>${entry.date} <button click.trigger='delete()'>X</button></div> 

    <div>${entry.note}</div> 

</template> 

entry.js

import {bindable} from 'aurelia-framework'; 

export class EntryCustomElement { 
    @bindable entry; 
    @bindable deleteFunction; 

    delete() { 
     this.deleteFunction(); 
    } 

} 

很顯然,在實際的實現中,你需要確保有什麼必然deleteFunction實際上是試圖調用之前的函數。

+0

感謝您的工作答案。這有幫助。然而,我在'app.js'視圖模型中有更多的功能,例如add(),edit(),read()等等。我需要爲每個人添加一個「call」綁定嗎? – akshayKhot

+0

那時我會重新考慮你的設計。你的組件與父組件的綁定方式太緊密了,這就是我在你直接調用許多父母方法時所說的。你可以看看使用自定義事件。 –

+0

我明白了。當你說'自定義事件'時,你的意思是[代理行爲](http://aurelia.io/hub.html#/doc/article/aurelia/templating/latest/templating-custom-elements/5)?這是我在搜索文檔「自定義事件」時首先彈出的內容。 – akshayKhot

1

使用綁定生命週期事件,您可以在Aurelia中獲得父視圖模式。

bind(bindingContext, overrideContext) { 
     this.parent = bindingContext; 
    } 

現在,您可以訪問所有從父視圖到您的視圖的變量和方法。

象下面這樣子視圖

this.parent.parentmethod(); 
+0

我不認爲這真的有效。 – LStarky

+1

它的工作原理。剛使用過。 – Hardycore