简体   繁体   English

javascript使用socket.io发送对象

[英]javascript sending object with socket.io

I am emiting object with socket.io 我用socket.io发射对象

socket.emit('object',{"object":collection});

but it happens sometimes when socket.io cant emit object right now because cant reach server, socket.io remembers that emit in memory, but collection changes in meantime and on server we recieve empty object. 但是有时候在socket.io由于无法到达服务器而无法发出对象的情况下,有时会发生这种情况,socket.io记得在内存中发出了该对象,但是在此期间集合发生了变化,并且在服务器上我们收到了空对象。

I tried also 我也尝试过

socket.emit('object',function(collection){
    return {"object":collection};
}(collection)

but it goes with same empty object (in the meanwhile collection is empty. 但它与同一个空对象一起使用(与此同时,集合为空。

Objects in JavaScript are passed by reference. JavaScript中的对象通过引用传递。 Any changes outside an asynchronous function to such an object are reflected later on in the object itself. 异步函数之外对此类对象的任何更改都会在对象本身中反映出来。

A simple solution is to copy the object by creating a new one which has all properties (and maybe methods...) of the original. 一个简单的解决方案是通过创建一个新对象来复制对象,该对象具有原始对象的所有属性(可能还有方法...)。

Example for arrays would be this neat little code: [].concat(collection); 数组的示例将是以下简洁的小代码: [].concat(collection); . But since we're talking objects here, that won't work. 但是由于我们在这里谈论对象,所以将不起作用。 With jQuery , this would be as easy as $.extend({}, collection); 使用jQuery ,就像$.extend({}, collection);一样简单$.extend({}, collection); , but since you didn't tag it, let's make our own version of that method. ,但是由于您没有对其进行标记,因此让我们制作该方法的自己的版本。

function extend( to, from, deep ) {
  // Double negation to force deep to be a boolean even if not provided. Thus: defaults to false.
  deep = !!deep;

  for( var i in from ) {
    if( deep ) {
      if( typeof from[i] == 'object' ) {
        // Array?
        if( from[i].length && typeof from[i].splice == 'function' ) {
          to[i] = [].concat(from[i]);
        }
        // nested object!
        else {
          to[i] = {};
          extend(to[i], from[i], deep);
        }
      }
      else {
        to[i] = from[i];
      }
    }
  }

  return to;
}

Applying it to socket.emit : 将其应用于socket.emit

socket.emit('object', {
  'object' : extend({}, collection, true)
});

Note that circular references will result in an infinite loop when deep copying. 请注意,深度复制时,循环引用将导致无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM