codecamp

EmberJS 将记录放入存储

将记录放入存储

您还可以将记录推送到存储的缓存中,而无需从应用程序请求记录。push()方法有助于将记录放入存储。

Ember.Route.extend({
   model: function() {
      this.store.push(//do the logic)
   }
});

在上面的代码中,push()方法将记录放入存储。

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Pushing Records Into The Store</title>
      <!-- CDN's-->
      <script src="/attachements/w3c/handlebars.min.js"></script>
      <script src="/attachements/w3c/jquery-2.1.3.min.js"></script>
      <script src="/attachements/w3c/ember.min.js"></script>
      <script src="/attachements/w3c/ember-template-compiler.js"></script>
      <script src="/attachements/w3c/ember.debug.js"></script>
      <script src="/attachements/w3c/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars">
         {{outlet}}
      </script>

      <script type="text/x-handlebars" data-template-name="index">
         <h3>Fruit Name and Color: </h3>
         {{#each item in model}}
            <p>Color of the  fruit: {{item.color}}<br>
            Name of the fruit: {{item.name}}</p>
         {{/each}}
      </script>

      <script type="text/javascript">
         App = Ember.Application.create();

         App.Color = DS.Model.extend({
            //data model
            color: DS.attr(),
            name: DS.attr()
         });

         App.ApplicationRoute = Ember.Route.extend({
            model: function() {
               //push() method pushes records into the store
               this.store.push('color', {
                  id: 1,
                  color: "Red",
                  name: "Apple"
               });

               this.store.push('color', {
                  id: 2,
                  color: "Yellow",
                  name: "Mango"
               });
              //returns the all stored data
               return this.store.all('color');
           }
         });
      </script>
   </body>
</html>

输出

让我们执行以下步骤,看看上面的代码如何工作:

  • 将上述代码保存在 model_pushing_records.html 文件中

  • 在浏览器中打开此HTML文件。

温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }