user1338121
user1338121

Reputation: 805

Access Index value while iterating Ember collection

Trying to access index value while iterating the ember collection, can access index value like this:

{{_parentView.contentIndex}}

But when trying to access the same index value in compare helper don't see the value. Any help on how to access index inside helper would be appreciated.

Code:

{{#each App.SampleController}}
    {{#view App.HomeView contentBinding="this"}}
        Index : {{_parentView.contentIndex}}
        {{#compare _parentView.contentIndex "0" operator="=="}} 
        {{/compare}
    {{/view}} 
{{/each}}

Output:

Index: 0 and the value getting passed into compare helper is `_parentView.contentIndex` as a string!

Compare Helper looks like this:

   Ember.Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {

   if (arguments.length < 3)
    throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

 operator = options.hash.operator || "==";

 var operators = {
    '==':       function(l,r) { return l == r; },
    '===':      function(l,r) { return l === r; },
    '!=':       function(l,r) { return l != r; },
    '<':        function(l,r) { return l < r; },
    '>':        function(l,r) { return l > r; },
    '<=':       function(l,r) { return l <= r; },
    '>=':       function(l,r) { return l >= r; },
    'typeof':   function(l,r) { return typeof l == r; }
};

if (!operators[operator])
    throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

console.log("operator is "+ lvalue +" and "+rvalue);
var result = operators[operator](lvalue,rvalue);
console.log("result from compare registerHelper is "+ result);

if( result ) {
    return options.fn(this);
} else {
    return options.inverse(this);
}

});

Upvotes: 0

Views: 489

Answers (1)

pangratz
pangratz

Reputation: 16163

The first parameter which is passed to your helper is actually a string which represents the path to the property which' value shall be resolved. So to get your lvalue you'd have to do something along those lines, see http://jsfiddle.net/pangratz666/DLPgN/:

Ember.Handlebars.registerHelper('compare', function(path, compareValue, options) {

    ...

    // options.contexts[0] is the passed context
    // path is the path to the property of the context
    var lvalue = Ember.getPath(options.contexts[0], path);
    var rvalue = parseInt(compareValue, 10); // convert to number since it's a string

    ...

    var result = operators[operator](lvalue, rvalue);

});​

Upvotes: 1

Related Questions