Handlebars.js自定义函数排序

use*_*844 2 javascript

我正在使用Handlebars来显示评论.

{{#each COMMENTS}}
     <div class="heightfix">
          <div class="commentIcon"></div>&nbsp;&nbsp;
             <label id="commentDate1" class="bold">{{COMMENTON}}</label>:&nbsp;
             <label id="commentCreator1" class="bold">{{COMMENTBY_FIRSTNAME}} {{COMMENTBY_LASTNAME}}</label>&nbsp;&nbsp;
             <label class="commentContent" id="commenttext_{{ID}}">{{COMMENTTEXT}}</label>
     </div>                                  
{{/each}}   
Run Code Online (Sandbox Code Playgroud)

在那些评论中,我有INDEX.我想根据他们的索引显示评论.评论0评论1评论2评论3 .....

如何使用自定义功能实现此目的?谢谢

Eth*_*own 11

方法1:自定义访问器

如果您可以控制上下文(并且可能已经执行),则可以使用属性访问器实现此操作.假设您的上下文包含混乱顺序的注释:

var context = {
    comments: [
        { idx:6, text:'violet' },
        { idx:1, text:'orange' },
        { idx:0, text:'red' },
        { idx:5, text:'indigo' },
        { idx:3, text:'green' },
        { idx:2, text:'yellow' },
        { idx:4, text:'blue' },
    ],
};
Run Code Online (Sandbox Code Playgroud)

您可以comments在渲染模板之前对数组进行排序(请注意,对于数值,您可以减去它们以获得自然顺序):

context.comments.sort( function(a,b) { return a.idx - b.idx; } );
Run Code Online (Sandbox Code Playgroud)

问题是修改上下文对象,您可能不想这样做.一种解决方案是提供一个自定义访问器,它将返回由某个自定义属性排序的注释.以下是我们如何做到这一点:

Object.defineProperty( context, 'commentsByIdx', {
    get: function() {
        // note that we call concat() to create a copy of
        // the array; otherwise we are modifying the
        // the original array, which is a side effect
        return this.comments.concat()
            .sort( function(a,b) { return a.idx - b.idx } );
    }
});
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到这个解决方案:http://jsfiddle.net/Jammerwoch/ShZLY/

方法2:把手块助手

另一种方法是实现Handlebars块助手.如果您对上下文没有太多控制(或者不希望使用自定义属性污染它),则此方法将更好地工作.只需注册Handlebars帮助器:

Handlebars.registerHelper('eachByIdx', function(context,options){
    var output = '';
    var contextSorted = context.concat()
        .sort( function(a,b) { return a.idx - b.idx } );
    for(var i=0, j=contextSorted.length; i<j; i++) {
        output += options.fn(contextSorted[i]);
    }
    return output;
});
Run Code Online (Sandbox Code Playgroud)

并在模板中调用它:

{{#eachByIdx comments}}
    <li>{{text}}</li>
{{/eachByIdx}}
Run Code Online (Sandbox Code Playgroud)

在这里看到它:http://jsfiddle.net/Jammerwoch/aeCYg/1/

总而言之,我发现第一种方法更可取,因为它创建了一个在Handlebars之外可能有用的新数据视图.此外,对于Handlebars代码的随意读者来说,它会更有意义.