2015-05-12 35 views
1

我有一個函數在點擊一個元素時被調用,我正在比較兩個數組。第一個數組使用過濾數組的表達式輸出到DOM。用ractivejs在關鍵路徑中使用助手

把手:

{{#each search(~/budgets, searchValue, 'accountName'):i}} 
    <p on-click="compareValues">{{accountName}}</p> 
{{/each}} 

JS:

Ractive.on('compareValues', function(target) { 
    if(Ractive.get(target.keypath + '.accountName') === Ractive.get(target.keypath.replace('budgets', 'accounts') + '.accountName') { 
     console.log(true); 
    } else { 
     console.log(false); 
    } 
}); 

一個例子target.keypath我得到的是"${search(budgets,searchValue,"accountName")}.4"

我想能夠比較這個結果數組與另一個數組,這也會通過表達式,所以我嘗試使用替換,以便它將切換表達式中使用的數組。

是否只能在已經通過表達式的數組上使用表達式,並且因爲我在更改數組時遇到未定義的結果而只能使用表達式?

+0

這對於target.keypath來說是一個奇怪的值。這是你的預期嗎?它應該代表你的'data'對象的結構。例如:如果data:{budgets:[{accountName:「one」}]}'那麼到accountName的keypath就是'budgets.0.accountName' – Keith

+0

@Keith我期望這個循環包含一個表達式,否則它會是在錯誤的地方尋找數據。 – silverlight513

回答

2

您可以只使用該事件上下文來獲取數組中的當前項目:

ractive.on('compareValues', function() { 
    var current = this.event.context, 
     index = this.event.index.i; 
}); 

否則,您可以定義爲搜索一個計算性能:

var r = new Ractive({ 
    el: document.body, 
    template: '#template', 
    computed: { 
     search: function(){ 
      var budgets = this.get('budgets'), 
       searchValue = this.get('searchValue'), 
       searchField = this.get('searchField') 

      return budgets.filter(function(each){ 
       return each[searchField] = searchValue; 
      }); 
     } 
    } 
}); 

然後你可以在模板中使用:

{{#each search:i}} 
    <p on-click="compareValues">{{accountName}}</p> 
{{/each}} 

並通過api:

ractive.get('search.' + index + '.accountName')