I'm having an issue where jQuery.ajax() is calling my data objects functions. For example, I have an object structure similar to the following:
var TestFactory = (function () {
var _id;
var _attributes;
return {
createObject: function (objectId) {
var value = null;
_id = objectId;
_attributes = {};
function _showErrorStatus() {
$('label')
.css('background-color', 'red')
.css('color', 'black')
.text('jQuery called me...');
}
function _attr(key, value) {
if (value == null) {
return _attributes[key];
}
_attributes[key] = value;
return this;
}
return {
id: _id,
attributes: _attributes,
showErrorStatus: _showErrorStatus,
attr: _attr,
}
}
}
})();
I'd like to use this object as the data value for my jQuery.ajax() call, as follows:
var myObject = TestFactory.createObject(12345);
myObject.attr('name', 'Fred Flinstone');
$.ajax({
url: '/echo/json/',
type: 'GET',
data: myObject,
dataType: 'json',
});
The issue I'm running into is jQuery.ajax() is calling the showErrorStatus() function from the object returned by the factory --nowhere in my code do I call this function.
I like the OOP qualities I get out of using this object, so is there any way to handle this case without a significant rewrite (e.g., dropping all my functionality from the "class")?
NOTE: I found it difficult to explain this problem, so here is a complete running example on jsfiddle.
Use JSON.stringify (not a jQuery method).
$.ajax({
url: '/echo/json/',
type: 'GET',
data: JSON.stringify(myObject),
dataType: 'json',
});
http://jsfiddle.net/HJ9AS/10/
It happens because it's a feature, though not documented as far as I can tell.
If you pass an object, then it assumes you want it to call any functions that are values of object properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With