2017-02-02 26 views
2

我對ref屬性/綁定的範圍感到困惑。我有兩個具有相同ref="activeTable"的HTML表格,每個表格有多個行,它們都具有相同的ref="activeRow"Aurelia ref基於元素的綁定範圍不同?

看到這個GistRun(複製下面的代碼)。

當我點擊一行的「編輯」按鈕時,單擊行的引用被傳入(不管表單或行被點擊)。但是,當我點擊桌子上的添加按鈕,參考表B 總是被傳入。

爲什麼ref被改寫爲activeTable但不activeRow

我目前的解決方案是使用ref="activeTableA"ref="activeTableB",但我仍然想知道發生了什麼。

我懷疑它與repeat和/或click.delegate有關。也許事件監聽器被添加到表和行的不同範圍?


HTML

<template> 
    <h4>Table A</h4> 
    <!-- Note the table ref --> 
    <table id="tableA" ref="activeTable"> 
    <thead> 
    <tr> 
     <th>Foo</th> 
     <!-- Passing in table ref --> 
     <th><button click.delegate="addRow(activeTable)">Add</button></th> 
    </tr> 
    </thead> 

    <tbody> 
     <!-- Note the row ref --> 
     <tr repeat.for="foo of foos" ref="activeRow"> 
     <td class="editable-cell">${foo.id}</td> 
     <!-- Passing in row ref --> 
     <td><button click.delegate="editRow(activeRow)">Edit</button></td> 
     </tr> 
    </tbody> 
    </table> 

    <h4>Table B</h4> 
    <table id="tableB" ref="activeTable"> 
    <thead> 
    <tr> 
     <th>Bar</th> 
     <th><button click.delegate="addRow(activeTable)">Add</button></th> 
    </tr> 
    </thead> 

    <tbody> 
     <tr repeat.for="bar of bars" ref="activeRow"> 
     <td class="editable-cell">${bar.id}</td> 
     <td><button click.delegate="editRow(activeRow)">Edit</button></td> 
     </tr> 
    </tbody> 
    </table> 
</template> 

JS

export class App { 
    foos = [ 
    {id: 0}, 
    {id: 1}, 
    {id: 2}, 
    {id: 3}, 
    {id: 4}, 
    {id: 5}, 
    {id: 6}, 
    {id: 7}, 
    {id: 8}, 
    {id: 9}, 
    ]; 

    bars = [ 
    {id: 10}, 
    {id: 11}, 
    {id: 12}, 
    {id: 13}, 
    {id: 14}, 
    {id: 15}, 
    {id: 16}, 
    {id: 17}, 
    {id: 18}, 
    {id: 19}, 
    ]; 

    addRow(table) { 
    console.log("Adding tow to", table); 
    } 

    editRow(row) { 
    console.log('Editing', row); 
    } 
} 

回答

3

ref允許你引用一個元素在你的綁定上下文的變量。通常,您的綁定上下文和您的頁面(或自定義元素)視圖模型是一樣的。但是,當您處理「模板控制器」(添加/刪除DOM元素的行爲)(例如repeat.for)時,可以更改綁定上下文。在repeat.for的情況下,對於中繼器的這個迭代,綁定上下文變成特定的項目

所以你覆蓋在你的頁面的虛擬機activeTable財產,但activeRow屬性被附加到foos和每個項目bars每個項目。這實際上是您想要的行爲(關於activeRow),因爲您可以將該行的特定元素傳遞給頁面VM上的函數。而對於activeTable,您需要爲每個表格ref使用不同的名稱。

+0

謝謝!我懷疑這與重複範圍有關。您對我在這裏和其他地方的Aurelia發展非常有幫助,非常感謝! – lebolo

+0

謝謝!那意義重大。 –