How to sort in ractive.js

时间:2016-10-20 12:44:02

标签: sorting ractivejs

I have got the following data (sample):

"data": {
    "eventsHeading": "Upcoming events",
    "eventsToBeDisplayed": 3,
    "allEventLinkText": "See all events",
    "eventsList": [
{
    "eventDate": "23/10/2016",
    "eventTitle": "EVENT INFO 1"
},
{
    "eventDate": "22/10/2016",
    "eventTitle": "EVENT INFO 2"
},
{
    "eventDate": "24/10/2016",
    "eventTitle": "EVENT INFO 3"
},
{
    "eventDate": "21/10/2016",
    "eventTitle": "EVENT INFO 4"
}
    ]
}

And I have something like this:

        <table>
            <tbody>
                {{#eventsList:i}}
                {{#i < eventsToBeDisplayed}}
                    <tr>
                                <td class="date-column">{{eventDate}}</td>
                                <td class="text-link truncate-text"><ux-anchor class="text-link" href="{{link}}">{{eventTitle}}</ux-anchor>
                    </tr>
                {{/}}
                {{/}}
            </tbody>
        </table>

So currently, this will loop to fetch only 3 Data and it will show:

23/10/2016   EVENT INFO 1

22/10/2016   EVENT INFO 2

24/10/2016   EVENT INFO 3

What i want to do is sort first the eventDate so i will fetch the incoming eventDate, so it will be like this:

21/10/2016   EVENT INFO 4

22/10/2016   EVENT INFO 2

23/10/2016   EVENT INFO 1

What is the best approach to do this?

1 个答案:

答案 0 :(得分:0)

您应该在ractive实例中对某些生命周期事件(或者可能是观察到的更改/自定义事件?)中的数据进行排序。由于您将日期作为日期字符串,因此需要先将它们解析为日期对象,然后才能进行比较。

this.set("eventsList",this.get("eventsList").sort( function (a, b) {
    var aParts = a.eventDate.split("/");
    var bParts = b.eventDate.split("/");
    return new Date(aParts[2],aParts[1],aParts[0]) < new Date(bParts[2],bParts[1],bParts[0]) ? -1 : 1;
}));  

工作小提琴:http://jsfiddle.net/pq7yrncv/