2016-04-15 292 views
0

我试图在角度服务内部扩展js本地数组以添加一些额外功能,而无需原型化全局对象。从阵列原型中删除元素

app.factory('Collection', function($http, $q) { 
    var Collection = function(arr) { 
     this.key = 'id'; 
     this._last = 0; 
     this._first = 77777777; //just big number. 
     this.append(arr); 
    } 
    Collection.prototype = new Array; 
    Collection.prototype.orderBy = function(n, reverse) { 
     if (reverse) { 
      this.sort(function(a, b) { 
       return b[n] - a[n]; 
      }) 
     } else { 
      this.sort(function(a, b) { 
       return a[n] - b[n]; 
      }) 
     } 
    } 
    Collection.prototype.spliceBy = function(key, val) { 
     for (var i = 0; i < this.length; i++) { 
      if (this[i][key] !== val) { 
       this.splice(i, 1); ///THIS NEVER HAPPENS !! 
       console.log('removed ' + i + ' from ', this); 
      } 
     } 
    } 
    Collection.prototype.subset = function(key, val) { 
     return this.filter(function(v) { 
      return (v[key] === val); 
     }); 
    } 
    Collection.prototype.add = function(obj) { 
     for (var i = 0; i < this.length; i++) { 
      if (this[i][this.key] > this._last) { 
       this._last = this[i][this.key]; 
      } 
      if (this[i][this.key] < this._first) { 
       this._first = this[i][this.key]; 
      } 
      if (this[i][this.key] === data[this.key]) { 
       if (override) { 
        this[i] = data; 
        console.log('updated uniquePush'); 
       } 
       return i; 
       break; 
      } 
     } 
     var id = this.push(data) - 1; 
     data._index = id; 
     return id; 
    } 
    return collection 
}); 

这是工作正常,除了spliceBy功能。 我需要筛选出没有value = x的元素; 例如在我的控制器

.controller(function($scope,Collection){ 

$scope.posts = new Collection; 

$scope.posts.add({id:1,type:'post'}); 
$scope.posts.add({id:2,type:'comment'}); 

//Collection is now [{id:1,type:post},{id:2,type:comment}]; 

//i want to remove all comments from array 
$scope.posts.spliceBy('type','comment'); 

}); 

但没有调用spliceBy时发生的情况:*(

+1

这并不期待权'Collection.prototype =新的Array;'你不能这样做,在ES5可以在ES6继承阵列虽然 – elclanrs

+1

@elclanrs不知道。关于那个但它在我的所有浏览器和科尔多瓦应用程序中都能正常工作:-) – Zalaboza

+0

如果它的工作正常,您为什么要发布这个问题?除了最新版本的Chrome/Edge(不支持FF),甚至需要使用(native)类语法之外,数组不可分。唯一的(也是我的意思是)使其工作的其他方法是编写一个包装类,它具有一个内部数组实例,它根据需要委派给它或者对Array.prototype进行monkey-patch。只要你尝试调用你的'子类'上的本地数组方法(例如拼接,缩小,移位),它就会失败。 –

回答

0

,如果你有两个元素的行删除,该spliceBy功能将无法工作,因为接头是从更新索引我到array.length试试这个:

Collection.prototype.spliceBy = function(key, val) { 
    var i = this.length; 
    while (i--) { 
     if (this[i][key] !== val) { 
      this.splice(i, 1); ///THIS NEVER HAPPENS !! 
      console.log('removed ' + i + ' from ', this); 
     } 
    } 
} 
+0

工程完美! :) – Zalaboza