@@ -20,6 +20,25 @@ module.factory('BaseObject', ($q) => {
2020 * Unsubscribe unnecessary overhead
2121 */
2222 close ( ) { }
23+
24+ /**
25+ * Prevents parallel queries and provides a stateful flag for view rendering
26+ *
27+ * Also allows you to permanently store cache to prevent any subsequent calls
28+ *
29+ * @param {string } name Name of property flag to use for caching the promise
30+ * @param {function } callback Executes the query and returns a promise
31+ * @param {boolean } [permanent] If the cache should be removed upon completion (default:false)
32+ */
33+ cache ( name , callback , permanent = false ) {
34+ // sets (truthy) flag reference to promise + avoids redundant calls
35+ return this [ name ] || this [ name ] = callback ( )
36+ // flag cleanup (doesn't affect chaining)
37+ . finally ( ( ) => {
38+ if ( ! permanent )
39+ this [ name ] = null ;
40+ } ) ;
41+ }
2342
2443 /**
2544 * object.save() - Convenience wrapper
@@ -28,9 +47,7 @@ module.factory('BaseObject', ($q) => {
2847 * Using `Promise.finally()` allows you to execute code on success OR fail withought affecting chaining
2948 */
3049 save ( ) {
31- // sets (truthy) flag reference to promise + avoids redundant calls
32- return this . saving = this . saving || ( this . id ? this . update ( ) : this . create ( ) )
33- . finally ( ( ) => this . saving = null ) ; // flag cleanup (doesn't affect chaining)
50+ return this . cache ( 'saving' , ( ) => this . id ? this . update ( ) : this . create ( ) ) ;
3451 }
3552
3653 /**
@@ -39,9 +56,7 @@ module.factory('BaseObject', ($q) => {
3956 * @note Use object.save() instead of calling this method directly
4057 */
4158 create ( ) {
42- // sets (truthy) flag reference to promise + avoids redundant calls
43- return this . creating = this . creating || $q . when ( this )
44- . finally ( ( ) => this . creating = null ) ; // flag cleanup (doesn't affect chaining)
59+ return this . cache ( 'creating' , ( ) => $q . when ( this ) ) ;
4560 }
4661
4762 /**
@@ -50,18 +65,14 @@ module.factory('BaseObject', ($q) => {
5065 * @note Use object.save() instead of calling this method directly
5166 */
5267 update ( ) {
53- // sets (truthy) flag reference to promise + avoids redundant calls
54- return this . updating = this . updating || $q . when ( this )
55- . finally ( ( ) => this . updating = null ) ; // flag cleanup (doesn't affect chaining)
68+ return this . cache ( 'updating' , ( ) => $q . when ( this ) ) ;
5669 }
5770
5871 /**
5972 * object.delete() - stubbed with example state flag updating
6073 */
6174 delete ( ) {
62- // sets (truthy) flag reference to promise + avoids redundant calls
63- return this . deleting = this . deleting || $q . when ( this )
64- . finally ( ( ) => this . deleting = null ) ; // flag cleanup (doesn't affect chaining)
75+ return this . cache ( 'deleting' , ( ) => $q . when ( this ) ) ;
6576 }
6677
6778 /**
0 commit comments