Merge pull request #1228 from shackbarth/jsdoc
[xtuple] / lib / backbone-x / source / collection.js
index b6e3b52..e036fd7 100644 (file)
@@ -261,6 +261,19 @@ white:true*/
     */
   XM.Collection = Backbone.Collection.extend(/** @lends XM.Collection# */{
 
+    /**
+      If true forwards a `post` dispatch request to the server against a 
+      function named "fetch" on the recordType name of the collection's model.
+      Otherwise calls `get` against the same.
+
+      This makes it easy to re-route fetch calls to functions that may have
+      much more complex logic than the normal `get` methodology and related
+      crud methods can support.
+
+      @default false
+    */
+    dispatch: false,
+
     fetchCount: 0,
 
     /**
@@ -361,14 +374,24 @@ white:true*/
         options.parse = true;
       }
       options.success = function (collection, resp, options) {
+        var data = resp;
+
         // Bail if this query result has been superceded by another
         if (fetchIndex < that.fetchCount) { return; }
 
+        // Dispatched fetches come back with a different response profile.
+        // Fix it, Felix.
+        if (that.dispatch) {
+          data = collection;
+          options = resp;
+          collection = that;
+        }
+
         var method = options.update ? 'update' : 'reset';
-        collection[method](resp, options);
+        collection[method](data, options);
         that.setStatus(XM.ModelClassMixin.READY_CLEAN);
         if (success) {
-          success(collection, resp, options);
+          success(collection, data, options);
         }
       };
       this.setStatus(XM.ModelClassMixin.BUSY_FETCHING);
@@ -404,20 +427,32 @@ white:true*/
     */
     sync: function (method, model, options) {
       var proto = model.model.prototype,
+        query = options.query || {},
         payload = {
-          query: options.query || {},
           nameSpace: proto.recordType.replace(/\.\w+/i, ''),
           type: proto.recordType.suffix(),
         },
-        parameters = payload.query.parameters;
+        parameters = query.parameters;
 
       // Clean up parameters
       if (parameters && parameters.length) {
         XM.Collection.formatParameters(proto.recordType, parameters);
       }
 
+
       if (method === 'read' && options.success) {
-        return XT.dataSource.request(this, "get", payload, options);
+        if (this.dispatch) {
+          method = "post";
+          payload.dispatch = {
+            functionName: "fetch",
+            parameters: query
+          };
+        } else {
+          method = "get";
+          payload.query = query;
+        }
+
+        return XT.dataSource.request(this, method, payload, options);
       }
 
       return false;