2016-07-08 9 views
0

私は絶対に輝かしいと思ってSocket.IOと実験しています。私はリアルタイムでリストを更新する非常に単純なアプリケーションを構築しようとしています。時間とIDでソートされたulリストに要素を追加します

My Nodeアプリケーションは、少なくともユニークなid(非数値)キーと項目あたりのユニックスタイムスタンプであるtimeキーを持つ配列を生成します。私が今行うことは、配列内の各アイテム(MustacheJSを使用)に<li>要素を生成し、HTML内の既存の<ul>リストにプッシュすることです。ここまでは順調ですね。

ここでは、常に新しい要素を押して、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 
*/ 

答えて

0

は、実際に私はそれを考え出しました。それは非常に簡単だった、なぜ私はそれが最初に明らかではなかったのか分からない。

  • サーバー側(ノードアプリ)、私はクライアントに送信された各IDのトラックを保つ私は新しいデータを持っている場合は
  • が、私はこのIDが既に
  • 私がやるに送信されなかったことを確認してください:ここではロジックです仕分けクライアント側は、直接ブラウザに(私はまだ最良の選択肢のために定住しているが、私はそれが可能だ知っている)

ほら...

関連する問題