2016-04-15 23 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機能以外は正常に動作しています。 値= 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

このdoesntのは、右 'Collection.prototype =新しい配列を探す;'あなたはES5であなたはしかしES6で配列をサブクラス化することができることを行うことはできません – elclanrs

+1

@elclanrsないように注意してください。そのことについてすべてのブラウザとコードバのアプリでうまく動作しています:-) – Zalaboza

+0

なぜうまく動作すれば質問を投稿しましたか?配列は、最新のバージョンのChrome/Edge(まだFFなし)、さらには(ネイティブ)クラス構文の使用を除いて、サブクラス化できません。それを動作させる他の方法は、必要に応じて委譲する内部配列インスタンス、またはmonkey-patch Array.prototypeを使用して、ラッパークラスを作成することだけです。あなたの 'サブクラス'でネイティブ配列メソッド(スプライス、リダクション、シフトなど)を呼び出そうとするとすぐに失敗します。 –

答えて

0

スプライスからインデックスを更新しているので、あなたは、行に削除するには2つの要素を持っている場合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

関連する問題