Skip to content

Instantly share code, notes, and snippets.

@zachshallbetter
Last active December 19, 2015 02:58
Show Gist options
  • Save zachshallbetter/5886512 to your computer and use it in GitHub Desktop.
Save zachshallbetter/5886512 to your computer and use it in GitHub Desktop.
Single responsibility principle (Decoupled code)
function AjaxForm($el) {
this.$form = $el;
this.form = $el[0]; // Internal state via properties
this.$form.on('submit', $.proxy(this.submit, this));
};
AjaxForm.prototype = {
submit: function(e) { // Named Functions
e.PreventDefault();
var this = this;
$.ajax({ // Single responsibility principle
url: _this.form.action,
type: _this.form.method,
success: $proxy(this.onSuccess, _this)
});
},
onSuccess: function(data) {
$({}).trigger('save success', data); // Loose coupling
this.reset();
},
reset: function() {
this.form.reset();
}
};
$('form#tweet').on('submit', function(e) { // Anon function
e.preventDefault();
var _this = this,
$tweets = $('#tweets'), // Tight coupling
$this = $(this),
$textarea = $this.find('textarea'),
tweet = $textarea.val();
$.ajax({
url: $this.attr('action'),
type: $this.attr('method'),
success: function() { // Nested Callback
$twets.append('li' + tweet + '</li'); // HTML templating
_this.reset();
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment