Reputation: 139
I have been assigned a project which involves a lot of jQuery. I am quite easy with it but the previous developer used the following code which is totally new to me and I am not aware of what it does.
$.extend({
ay: {
ajaxRequest: {
abort: function(){}
}
}
});
I can tell that ay
is directory name in which all of the project's configuration files and templates are. Can anybody explain this code? Thanks
I've also seen this code in the project:
$.ay.ajaxRequest = $.ajax({
data: {
ay: {
action: 'update',
element: {
id: $(this).data().id
},
input: {
name: $(this).attr('name'),
value: $(this).val()
}
}
},
type: 'post'
});
In this sample code, there is no url or path to php script, can you explain this as well?
Upvotes: -1
Views: 163
Reputation: 75317
He's using jQuery.extend()
to extend jQuery to add an ay
attribute, which is an object with an ajaxRequest
attribute, which is another object with an abort
attribute which is an empty function (noop).
So you could do;
jQuery.ay.ajaxRequest.abort();
If you wanted, which would do absolutely nothing.
As to why this is useful; you'll have to inspect the rest of the code to see where he's calling it.
For more info on extending jQuery see the docs.
EDIT: To address the second part, if he's extending jQuery before you see that code, then he's replacing the ajaxRequest
with the jqXHR returned by jQuery.ajax()
. If he's extending jQuery after that code, then he's overwriting the abort()
method to do nothing; basically no-one will be able to cancel the AJAX request.
Using jQuery.extend()
to do this is quite weird, I'd do:
jQuery.ay.ajaxRequest.abort = jQuery.noop;
He must be declaring the URL for that AJAX request using jQuery.ajaxSetup()
(which sets AJAX defaults).
Upvotes: 4
Reputation: 21742
The code adds a property called ay to The jQuery object ($) making code such as $.ay.ajaxRequest.abort()
possible.
If you pass one argument to extend that argument will extend the jQuery namespace it self. That means each property of the argument will be cloned to the jQuery object. In your case there's a single property called ay which is cloned to the jQuery object. Calling extend with an object that has one property is equal to
$.ay = {
ajaxRequest : {...}
};
Upvotes: 1