Skip to content

Instantly share code, notes, and snippets.

@sunpietro sunpietro/index.html
Last active Aug 29, 2015

Embed
What would you like to do?
An example of implementing a module pattern with promises
<body>
<div class="task api-1"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script id="user-profile" type="text/template">
<div class="user">
<img src="<%= picture %>" alt="">
<div class="info">
<h3><%= name.first%> <%= name.last%></h3>
<dl>
<dt>Address:</dt>
<dd><%= location.street%><br/><%= location.zip%> <%= location.city%>, <%= location.state%></dd>
<dt>Phone:</dt>
<dd><%= cell%></dd>
<dt>Email:</dt>
<dd><%= email%></dd>
</dl>
</div>
</div>
</script>
<script src="module-user-promise.js"></script>
</body>
(function () {
API = window.API || {};
API.User = function User(gender) {
var userObject = {};
var defer = $.Deferred();
var createProfile = function () {
$('.api-1').append(_.template($('#user-profile').html(), userObject));
};
$.getJSON('http://api.randomuser.me/?gender=' + gender, defer.resolve);
defer.then(function (result) {
userObject = result.results[0].user;
});
return {
getName : function () {
defer.done(function () {
console.log(userObject.name.first + ' ' + userObject.name.last);
});
},
getAddress : function () {
defer.done(function () {
console.log(userObject.location);
});
},
updateAddress : function (data) {
defer.done(function () {
_.assign(userObject.location, data);
if ($('.user').length) {
$('.user').remove();
createProfile();
}
});
},
renderProfile : function () {
defer.done(function () {
createProfile();
});
}
};
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.