javascript - 我如何更新来自差异 socket.io 事件的消息?

标签 javascript jquery socket.io

我正在使用具有差异事件 channelName1channelName2 的 api>

//...this the realtime record
socket.on(channelName1, message => {
      console.log(channelName1, message1);
      //this return single item list in realtime`[{"price":100,"size":0.001}]`
 });

//realtime snapshot collection of records
socket.on(channelName2, message => {
   console.log(channelName2, message2);
   //this return the collection `[{"price":100,"size":0.01}, {"price":200,"size":0.02} ]`
   $('#live').text(message2)
});

如果我发现 price":100 出现在集合 message2 中,我想更新 message2 的大小,所以更新后 message2 将

[{"price":100,"size":0.001}, {"price":200,"size":0.002} ]

谁能指导我如何进行从 channelName1 到 ChannelName2 数据的更新?

最佳答案

您必须将单件元素存放在某个地方,当收集品到达时您需要:

  1. 使用 map 处理集合中的每一项.
  2. 对于每个项目,尝试 find它在存储的单个项目中。
  3. 如果找到,请更改大小。

我还在集合中包含了一条无法找到的记录,因此您可以看到那里发生了什么:它保持不变。

忽略我为模拟套接字所做的小改动。希望您能看到我正在做的事情的大局。

希望这对您有所帮助,祝您编码愉快。

// Stores each single item that arrives.
let singleItems = [];

// ...this is the realtime record.
function socketOn1(channelName1, message1) {
  console.log(channelName1, message1);

  // Store each single item as it arrives.
  singleItems.push(message1[0]);
};

// realtime snapshot collection of records
function socketOn2(channelName2, message2) {
  console.log(channelName2, message2);

  // For each element in the collection, find
  // the same record in the single items and
  // if found, update the price.
  results = message2.map((elem) => {
    found = singleItems.find(
      (single) => single.price === elem.price
    )
    if (found) {
      elem.size = found.size
    }
    return elem
  })

  console.log('results:')
  console.log(results)
};


// This stuff just simulates stuff arriving to sockets.
// You can ignore it if you want. But look at the order
// in which they are called.

let singleItemsMock = [{
    "price": 100,
    "size": 0.01
  },
  {
    "price": 50,
    "size": 0.02
  },
  {
    "price": 25,
    "size": 0.03
  },
  {
    "price": 10,
    "size": 0.04
  }
]

let collectionMock = [{
    "price": 100,
    "size": 0.001
  },
  {
    "price": 50,
    "size": 0.002
  },
  {
    "price": 13,
    "size": 0.005
  }
]

socketOn1(null, [singleItemsMock[0]])
socketOn1(null, [singleItemsMock[1]])
socketOn1(null, [singleItemsMock[2]])
socketOn1(null, [singleItemsMock[3]])

socketOn2(null, collectionMock)

关于javascript - 我如何更新来自差异 socket.io 事件的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58072039/

相关文章:

javascript - 设置属性值的 Ember 问题

javascript - 非IE浏览器鼠标捕获?

jquery - 如何知道 jquery resizing 中正在使用哪个句柄

javascript - Websocket 服务器连接到 Django 以转发广播

javascript - 如何维护对正确对象的引用?

javascript - 使用 NodeJS 和 Electron 使用操作系统的默认应用程序(带有 Word 的 docx 等)打开外部文件

javascript - 一键单击即可用随机值填充多个输入

javascript - 无法使用jquery从函数中获取值

jquery - 当不透明度为 0% 时删除元素的点击

javascript - 使用 jwt 和 socket io 的身份验证流程