Custom for-loop helper for EmberJS/HandlebarsJS

倾然丶 夕夏残阳落幕 提交于 2019-12-01 01:59:19

I solved this myself after trying for a long time.

The HandlebarsJS method (as described on the site) is no longer valid for EmberJS, it's now as follows:

function forLoop(context, options) {
    var object = Ember.getPath(options.contexts[0], context);
    var startIndex = options.hash.start || 0;

    for(i = startIndex; i < object.length; i++) {
        options(object[i]);
    }
}

Heck, you could even extend the for-loop to include an index-value!

function forLoop(context, options) {
    var object = Ember.getPath(options.contexts[0], context);
    var startIndex = options.hash.start || 0;

    for(i = startIndex; i < object.length; i++) {
        object[i].index = i;

        options(object[i]);
    }
}

This is a working for-loop with variable start index. You use it in your templates like so:

{{#for anArray start=1}}
    <p>Item #{{unbound index}}</p>
{{/for}}

Here is how I did it (and it works !!!)

First, i had in my model a 'preview' property/function, that just return the arrayController in an array :

objectToLoop = Ember.Object.extend({ 
        ...
    arrayController: [],
    preview: function() {
        return this.get('arrayController').toArray();
    }.property('arrayController.@each'),
        ...
});

Then, I add a new Handlebars helper :

Handlebars.registerHelper("for", function forLoop(arrayToLoop, options) {
    var data = Ember.Handlebars.get(this, arrayToLoop, options.fn);

    if (data.length == 0) {
        return 'Chargement...';
    }

    filtered = data.slice(options.hash.start || 0, options.hash.end || data.length);

    var ret = "";
    for(var i=0; i< filtered.length; i++) {
        ret = ret + options.fn(filtered[i]);
    }
    return ret;     
});

And thanks to all this magic, I can then call it in my view :

<script type="text/x-handlebars"> 
    <ul>
        {{#bind objectToLoop.preview}}
            {{#for this end=4}}
                <li>{{{someProperty}}}</li>
            {{/for}}
        {{/bind}}
    </ul>
</script>

And that's it.

I know it is not optimal, so whoever have an idea on how to improve it, PLEASE, make me know :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!