-1

Ik have a JavaScript object with lots of properties and calculated properties (which are functions), which I want to send to the server. Now when I call this method

resource.save({ id: vm.allData.id }, vm.allData);

(where vm.allData holds the object) only the properties are serialized, and not the results of the functions.

Is it possible to serialize function results also?

So as an example this little object

function Example() {
    var obj = this;
    this.propa = 5;
    this.propb = 10;
    this.total = function () {
        return obj.propa + obj.propb;
    }
}

I want to serialize property propa, property propb and (calculated) property total

Is that possible?

Michel
  • 23,085
  • 46
  • 152
  • 242

1 Answers1

0

You need to provide some way to evaluate the values to be saved. You can do this outside of the resource.save() or i.e. use transformRequest to do this on the fly. The general concept is to have service to provide dedicated resource like this:

factory("someService", function ($resource) {
  return $resource(
    'http://your.url.com/api', {}, {
      get: {
        method: 'POST',
        transformRequest: function(data, headers) {
          var toBeSaved = {};
          for (key in data) {
            if (data.hasOwnProperty(key)) {
              if(typeof data[key] == function) {
                toBeSaved[key] = data[key]();
              } else {
                toBeSaved[key] = data[key];
              }
            }
          }
          return toBeSaved;
        }
      }
    });
});

Beware the assumption made here is that the functions don't require any arguments. Also note that this is just a draft concept so please refer to the $resource documentation for more details.

ciekawy
  • 2,238
  • 22
  • 35