Ich experimentiere mit Socket.IO, die ich absolut genial finde. Ich versuche eine sehr einfache App zu erstellen, die eine Liste in Echtzeit aktualisiert.Fügen Sie Element zu ul Liste nach Zeit und ID
Meine Knoten App generiert ein Array mit mindestens einem eindeutigen id
(nicht numerischen) Schlüssel und einem time
Schlüssel, der ein Unix-Zeitstempel pro Element ist. Was ich jetzt mache ist, dass ich ein <li>
Element für jedes Element in diesem Array (unter Verwendung MustacheJS) erzeuge und das Los in eine bestehende <ul>
Liste in meinem HTML verschiebe. So weit, ist es gut.
Jetzt möchte ich es ein bisschen besser machen, indem ich nur neue Elemente dränge und sie je nach dem time
Schlüssel bestelle, anstatt eine volle Liste die ganze Zeit zu schieben.
Was ist der beste Weg, dies zu tun?
Hier einige Blindkode meines Anwendungsfall zu veranschaulichen:
// 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
*/