Last active
December 19, 2015 02:58
-
-
Save zachshallbetter/5886512 to your computer and use it in GitHub Desktop.
Single responsibility principle (Decoupled code)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('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