Javascript:对象数组VS具有唯一属性的对象?

时间:2017-07-22 23:31:34

标签: angularjs arrays json indexing socket.io

我正在为我公司的实时Web应用程序工作,我正在使用带有socket.io的MEAN堆栈在特定套接字室的所有客户端中提供实时$ scope变量更新。

我目前正在使用动态的对象数组,能够添加或删除元素,我必须为每个数组元素设置$ watch函数,并在其各自的$ watch函数中传递元素的_id。问题是:当元素被移除时,AngularJS无法通过它的_id来跟踪元素在数组中的位置。

所以我在考虑,不是使用数组来存储对象,而是使用具有每个元素id的唯一属性的对象,如下所示:

$scope.mainObj = {
   '1234': {name: 'bob', age: 21},
   '1235': {name: 'william', age: 23},
   '1236': {name: 'rob', age: 28}
};

而不是:

$scope.mainArray = [
   {_id: '1234', name: 'bob', age: 21},
   {_id: '1235', name: 'william', age: 23},
   {_id: '1236', name: 'rob', age: 28}
];

首先,我认为这将消除必须索引我的数组并且必须在房间中的每个客户端中定位元素位置以更新变量的问题,通过更新以元素的_id命名的属性来使更改成为原子。

这是否会带来任何性能问题或其他问题?就像我说的,数组索引是可有可无的,通过_id检测元素的查找函数不是必需的,更新错误元素的机会将是0,因为使用索引数组方法存在错误元素的最小机会当有太多用户添加,删除或编辑数组元素时更新。

那么,这是个好主意吗?如果没有,我怎么能观察数组元素,在watch函数中传递元素_id并且不会丢失每个元素的跟踪?我现在拥有的是:

$scope.setWatch = function (element, id) {
  $scope.$watch(x, function() {
    console.log('watching: ' + element);
    console.log('do something with : ' + id);
  });
}

socket.on('addArrayElm', function (res) {
  var id = res.id;
  $scope.mainArray.push(new arrayElement(id));//creates new element from constructor with received _id from server
  $scope.mainArrayIndex.push(id);//push id in index array
  var i = $scope.mainArrayIndex.length - 1;//get the pushed element index in array
  var j = 'mainArrayIndex[' + i + '].name';//construct string to use in $watch function referring to the element in array's position 'i'
  $scope.setWatch(j, z);
  $scope.$apply();
});

主要问题是:如果我删除一个元素,比如第二个元素(index = 1),$ watch函数不会被销毁,并且因为它将index = 1作为参数,它将被触发采用index = 1的元素,因此使用了错误的_id。

我该怎么办?

谢谢!

0 个答案:

没有答案
相关问题