1

Consider this object:

function Cow() {
var self = this;

self.color = "blue";
self.weight=55;
}

Cow.prototype.Speak = function(){
 var self=this;
 alert('moo. i\'m a ' + self.color + ' cow.');
}

var bessy = new Cow();

I'm running into an issue when I try to do $.ajax(...) and pass in 'bessy' as the data parameter. My intention is for the data properties to be serialized and passed over the wire But it will actually execute Speak() upon the ajax call. This is an overly simple example, but highlights the problem I'm having.

To solve this, I've created a function that accepts an object and conditionally deletes members (such as functions). I then pass a copy of the target object to that function, and use my new simplified copy of the object for the ajax call. This seems really cumbersome. Is this a common problem? How do others deal with this? It seems like overkill to create separate DTO JS objects for this purpose because then, when I add a new property, it would need to be added in two places.

Would appreciate any thoughts.

Thanks... -Ben

5
  • If your data properties were part of a object that was defined on a property of this, it would be easy to instead pass that property object rather than the entire instance, and would only require modifying that one object to add more properties. Commented Jun 24, 2014 at 19:52
  • you would want to trim all key-value pairs that have a typeof value === "function" Commented Jun 24, 2014 at 19:52
  • its Cow.prototype btw. Commented Jun 24, 2014 at 19:59
  • @KevinB, are you suggesting having a subobject under Cow, so that it would look something like Cow.data.color? Commented Jun 24, 2014 at 20:17
  • Yes, similar to how options are usually handled. You have an instance, in this case Cow, that has methods (Speak) and options (weight and color). Commented Jun 24, 2014 at 20:18

1 Answer 1

4

You can do it by easily converting the object into json string. JSON.stringify(bessy) will let you have json string of the bessy variable. Send that to the server and convert into object again by using json_decode.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.