我正在尝试Socket.IO,我发现它非常出色。我正在尝试构建一个非常简单的应用程序,以实时更新列表。
我的Node应用程序生成的数组至少包含一个唯一的id
(非数字)键和一个time
键,该键是每个项目的unix时间戳。现在,我要做的是为该<li>
数组中的每个项目生成一个元素(使用MustacheJS),然后将其推送到<ul>
HTML中的现有列表中。到现在为止还挺好。
现在,我想通过仅推送新元素并根据time
键对它们进行排序,而不是一直推送完整列表来使它更好一点。
最好的方法是什么?
这是一些虚拟代码来说明我的用例:
// Let's say this is my initial array
array_one = [
{
id: 'one_1',
time: '1467982149',
content: 'Content one_1'
},
{
id: 'one_2',
time: '1467983149',
content: 'Content one_2'
},
{
id: 'one_3',
time: '1467981149',
content: 'Content one_3'
},
{
id: 'one_4',
time: '1467482149',
content: 'Content one_4'
}
];
/*
Here I take that first array, generate a <li></li> element for
each item in it, obtaining something like this :
<li data-id="one_1" data-time="1467982149">Content one_1</li>
I store all of those in an array, let's say "allMyItems"
*/
/*
I have all of my <li> elements, so now I push them to my <ul>
list using a Socket.IO event and jQuery on the client side.
It looks like this :
$('ul').html( 'allMyItems' );
*/
// Later fetch the data again, and there's old but also new elements
// and this is where I don't know how to do it. You can see it's
// mostly the same array but with two new elements
array_one = [
{
id: 'one_1',
time: '1467982149',
content: 'Content one_1'
},
{
id: 'one_2',
time: '1467983149',
content: 'Content one_2'
},
{
id: 'one_3',
time: '1467981149',
content: 'Content one_3'
},
{
id: 'one_4',
time: '1467482149',
content: 'Content one_4'
},
{
id: 'two_1',
time: '1467432149',
content: 'Content two_1'
},
{
id: 'two_2',
time: '1467232149',
content: 'Content two_2'
}
];
/*
What I want to do now, is :
1. Update the front-end <ul> list with just the two new items
2. Correctly sort that <ul> using the 'time' key
*/
其实我知道了。这很简单,我不知道为什么一开始它并不明显。这是逻辑:
这里 ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句