Skip to content

Instantly share code, notes, and snippets.

@eccegordo
Last active December 21, 2015 05:58
Show Gist options
  • Save eccegordo/6260354 to your computer and use it in GitHub Desktop.
Save eccegordo/6260354 to your computer and use it in GitHub Desktop.
See it in action
http://jsbin.com/omIZeq/4
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<link href="http://getbootstrap.com/dist/css/bootstrap.css" rel="stylesheet" type="text/css" />
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0-rc.3/handlebars.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/ember.js/1.0.0-rc.6/ember.min.js"></script>
<script src=" http://builds.emberjs.com.s3.amazonaws.com/ember-data-0.13.js"></script>
<title>Ember JS Cookie Maker (with async)</title>
</head>
<body>
<script type="text/x-handlebars">
<div class="container">
<h1>Cookie Maker</h1>
<h4>Ember JS Promises Example</h4>
{{#linkTo "cookies" }} Start making cookies {{/linkTo}}
<hr />
<div class="well well-sm"> {{ outlet }}</div>
</div>
</script>
<script type="text/x-handlebars" data-template-name="cookies">
<button {{action askForCookie}} type="button" class="btn btn-primary btn-sm">Ask For Cookie</button>
<br />
<br />
<div class="row">
<div class="col-xs-6 col-md-4">
<ul class="list-group">
{{#each controller}}
<li class="list-group-item">
{{#linkTo "cookies.cookie" this }}
<div>
<span class="label label-primary">ID: {{id}}</span>
<h4> <span class="label label-info">{{qty}}</span> {{kind}}</h4>
<span class="label label-success">{{deliveryStatus}}</span>
</div>
{{/linkTo}}
</li>
{{/each}}
</ul>
</div>
<div class="col-xs-12 col-md-8">
<div class="well well-sm"> {{ outlet }}</div>
</div>
</div>
</script>
<script type="text/x-handlebars" data-template-name="cookies/cookie">
<h4> <span class="label label-info">{{qty}}</span> {{kind}}</h4>
<span class="label label-success">{{deliveryStatus}}</span>
</script>
</body>
</html>
App = Ember.Application.create();
App.SYNCH = "synchronous mode";
App.ASYNCH = "asynchronous mode";
// Router
App.Router.map(function() {
this.resource("cookies", { path: "/cookies" }, function(){
this.route("cookie" , { path: ":cookie_id" });
this.route("request" , { path: "request" });
});
});
// Routes
App.CookiesRoute = Ember.Route.extend({
events: {
askForCookie: function() {
var getCookieFromBakery;
getCookieFromBakery = App.cookieMaker(App.SYNCH);
console.log( "asked for cookie = " + getCookieFromBakery.get('deliveryStatus') );
getCookieFromBakery = App.cookieMaker(App.ASYNCH);
console.log( "asked for cookie = " + getCookieFromBakery.get('deliveryStatus') );
}
},
model: function() {
return App.CookieStore;
}
});
App.CookiesCookieRoute = Ember.Route.extend({
model: function(params) {
var cookies = App.CookieStore;
var matchedCookie = null;
cookies.forEach(function(item, index) {
console.log('Cookie %@: %@'.fmt(index+1, item));
if (item.id === params.cookie_id) {
// Found match
matchedCookie = item;
}
});
return matchedCookie;
}
});
// Controllers
// App.CookiesController = Ember.ArrayController.extend({});
// App.CookiesCookieController = Ember.ObjectController.extend({});
// Models (basic ember objects)
App.Cookie = Ember.Object.extend({
id: null,
qty: null,
kind: null,
deliveryStatus: null
});
// Just a basic Ember Array
App.CookieStore = Ember.A([]);
///////////////////////////////////
// Extra Utility Functions
///////////////////////////////////
App.cookieCounter = 0;
App.cookieBatchSize = function() {
// Quantity of cookie batches is random
var randomQty = Math.floor(Math.random() * (12 - 1) + 1);
return randomQty;
};
App.cookieMaker = function(mode) {
var cookie, cookieID, cookieQty, cookiePromise, promiseKept;
// Quantity of cookies is random
cookieQty = App.cookieBatchSize();
// Create the cookie object
cookie = App.Cookie.create({});
// Increment counter and use as id
// simulate database id
App.cookieCounter = App.cookieCounter + 1;
cookieID = App.cookieCounter;
// Give our cookie an ID
cookie.set('id', cookieID);
if (mode === App.SYNCH) {
// cookies made synchronously
cookie.set('qty', cookieQty);
cookie.set('kind', "Chocolate chip");
cookie.set('deliveryStatus', "cookie delivered immediately");
} else if (mode === App.ASYNCH) {
// cookies made asynchronously
// use promises
cookiePromise = App.cookieSlowBake(cookie);
// Call the then function on the promise
promiseKept = cookiePromise.then(App.cookieDeliveredSuccessfully, App.cookieNotDelivered);
//App.CookieStore.pushObject(promiseKept);
return promiseKept;
} else {
// if mode is undefined then can't make cookies
cookie.set('qty', 0);
cookie.set('kind', null);
cookie.set('deliveryStatus', "not delivered cookie maker offline");
}
// Just to confirm our cookie was made
console.log("the bakery has your cookies");
console.log(cookie);
// We need to persist the object to some collection
// Save to the cookie store (ember array)
App.CookieStore.pushObject(cookie);
return cookie;
};
App.cookieDeliveredSuccessfully = function(value) {
alert("Slow baked cookie is ready. Enjoy the " + value.get('qty') + " " + value.get('kind'));
App.CookieStore.pushObject(value);
};
App.cookieNotDelivered = function(reason) {
alert("Something happened with the oven sorry no cookies. Reason: %s", reason);
};
App.cookieSlowBake = function(cookieDough) {
// This is a simulation of a long running process.
// The cookies take longer to bake but they are extra delicious
var cookieQty = App.cookieBatchSize();
cookieDough.set('qty', cookieQty);
cookieDough.set('kind', "slow baked chocolate chips");
var bakedCookiePromise = new Ember.RSVP.Promise(function(resolve, reject){
var bakeTime = 2000; // milliseconds
var bakedCookie = false;
// slow baking in the setTimeout oven
// To simulate duration of time we are going to use the Ember.run.later method
// This works like setTimeout
Ember.run.later(cookieDough, function() {
// code here will execute within a RunLoop in about the bakeTime with this == cookieDough
cookieDough.set('deliveryStatus', "cookie delivered later after baking " + bakeTime);
bakedCookie = true;
resolve(cookieDough);
}, bakeTime);
});
return bakedCookiePromise;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment