Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!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(function(value) {
      // success
      alert("Your slow baked cookies are ready to eat");
      App.CookieStore.pushObject(value);
    }, function(value) {
      // failure
      alert("Something happened with the oven sorry no cookies.");
    });
  
    //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.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);    
    
//    if (bakedCookie) {
//      resolve(cookieDough); // The baked cookie will be delivered upon success
//    } else {
//      reject(this); // If a problem happens then return rejection
//    } 
  });
  return bakedCookiePromise;
};   
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
mikegrassottipro
0viewers