I recently read a blog post about having your code rely as little on the DOM as possible (i.e. keep as much out of the $(document).ready() function as possible). I’ve been successful in doing this with things like creating view modules like this:
var View = function (e) {
this.element = e;
};
View.prototype = {
show: function () {
this.element.fadeIn();
},
//More manipulation functions
};
$(document).ready(function () {
var myView = new View($('#element'));
myView.show();
});
I can’t seem to find a way to wrap AJAX calls into an object so they’re not depending on the DOM being loaded and so I don’t have to write something like this every time I make an AJAX call:
$.ajax({
url: "signout.php",
type: "POST",
dataType: "json",
error: function (jqXHR, textStatus, errorThrown) {
alert('An error occured while trying to log out.');
},
success: function (data, textStatus, jqXHR) {
settingsWidget.getAction('#settings').triggerAction(500, function () {
WIDGETS.setOnTop('#login', SideEnum.RIGHT);
});
},
complete: function (jqXHR, textStatus) {}
});
Is there a design pattern that I can use to achieve what I’m trying to do? Also, would it be best to pass the jQuery DOM object to the View object or just the selector and grab the DOM object inside of the View object?
Dirtying up the DOM has always been a problem. Backbone.js is great, it helps give a lot of structure to your code. The module pattern by Douglas Crockford will help provide encapsulation for a lot of your code as well.
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
A great synopsis of some design patterns
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
And this is what I currently use as a design pattern
https://github.com/bmarti44/jq-mod-pat
What you use is up to you, but you should be fine doing ajax calls with any of these patterns. Hopefully one of these will give you some inspiration.