@@ -35,31 +35,42 @@ angular.module('<%= scriptAppName %>')
3535 socket : socket ,
3636
3737 /**
38- * Register listeners to sync a collection with socket.io
38+ * Register listeners to sync an array with a database collection through socket.io
39+ *
40+ * Takes the array we want to sync, the model namespace that socket updates are sent from,
41+ * and an optional callback function after new items are updated.
42+ *
43+ * @param {Array } array
44+ * @param {String } namespace
45+ * @param {Function } cb
3946 */
40- syncCollection : function ( collection , itemName ) {
47+ syncArray : function ( array , namespace , cb ) {
48+ cb = cb || angular . noop ;
4149
4250 /**
4351 * Syncs item creation/updates on 'model:save'
4452 */
45- socket . on ( itemName + ':save' , function ( newItem ) {
46- var oldItem = _ . find ( collection , { _id : newItem . _id } ) ;
47- var index = collection . indexOf ( oldItem ) ;
53+ socket . on ( namespace + ':save' , function ( newItem ) {
54+ var oldItem = _ . find ( array , { _id : newItem . _id } ) ;
55+ var index = array . indexOf ( oldItem ) ;
4856
4957 // replace oldItem if it exists
5058 // otherwise just add newItem to the collection
5159 if ( oldItem ) {
52- collection . splice ( index , 1 , newItem ) ;
60+ array . splice ( index , 1 , newItem ) ;
5361 } else {
54- collection . push ( newItem ) ;
62+ array . push ( newItem ) ;
5563 }
64+
65+ cb ( array )
5666 } ) ;
5767
5868 /**
5969 * Syncs removed items on 'model:remove'
6070 */
61- socket . on ( itemName + ':remove' , function ( newItem ) {
62- _ . remove ( collection , { _id : newItem . _id } ) ;
71+ socket . on ( namespace + ':remove' , function ( newItem ) {
72+ _ . remove ( array , { _id : newItem . _id } ) ;
73+ cb ( array )
6374 } ) ;
6475 }
6576 } ;
0 commit comments