Skip to content

Instantly share code, notes, and snippets.

@jocoonopa
Last active December 28, 2015 20:49
Show Gist options
  • Save jocoonopa/7560283 to your computer and use it in GitHub Desktop.
Save jocoonopa/7560283 to your computer and use it in GitHub Desktop.
<!doctype html>
<html lang="zh-tw">
<head>
<meta charset="UTF-8">
<title>Deferred Object Simple Demo</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" value="" />
<div class="response"></div>
</body>
<script>
$(function () {
var deferredObj = (function () {
var view = {
setup: function () {
this.$input = $( 'input' );
this.$resDiv = $( '.response' );
}
},
controller = {
onAjaxEvent: function () {
view.$input.on( 'blur', function () {
var setModel = function () {
model.post.data = view.$input.val();
return $.Deferred().resolve();
};
// The chain process start
$.when( setModel() )
.then(function () {
return $.post( model.url, model.post );
})
.done(function ( res ) {
view.$resDiv.html( res );
})
.fail(function () {
alert( 'ajax error' );
})
.done(function () {
view.$resDiv.fadeIn( 500 );
});
})
.on( 'focus', function () {
view.$resDiv.fadeOut( 500 );
});
}
},
model = {
'post': {
'data': 0
},
// Just use to test ajax respond, it can be whatever you want
'url': 'ajax.php'
};
return {
init: function () {
view.setup();
controller.onAjaxEvent();
}
};
});
var oDeferred = new deferredObj();
oDeferred.init();
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment