Search code examples
javascripthandlebars.jsractivejs

Using helpers inside a keypath with ractivejs


I have a function that is called on click of an element and I am comparing two arrays. The first array is printed out to the DOM with an expression that filters the array.

Handlebars:

{{#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);
    }
});

An example target.keypath I get is "${search(budgets,searchValue,"accountName")}.4".

I would like to be able to compare this resulted array with another array that would also go through the expression so I tried to use a replace so that it would switch the arrays that are being used in the expression.

Is it only possible to use the expression on an array that has already gone through the expression and already has a result as I am getting undefined when changing the array?


Solution

  • You may be able just to use the event context to grab the current item in the array:

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

    Otherwise, you can define a computed property for the search:

    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;
                });
            }
        }
    });
    

    Then you can use in the template:

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

    And via the api:

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