promisecanjscanjs-model

The best way to show loader message during model.list loading


I created a simple MVC application with canjs for an users list, by using can.Model.List. Since my request could take more than 5 second, I would add in the view a little preload message/image during the loading.

i.e. I would something like this (I'm using mustache)

var users = new Users.List({});
element.html(can.view('myView', users);

with this template:

{{#if loading}}
   <p>Loading, please wait...</p>
{{else}}
   <ul>
      {{#each this}}
         <li>User {{ name }} {{ surname }}</li>
      {{/each}}
   </ul>
{{/if}}
</ul>

I can solve by having a new observable variable, but I think there's a better way to direct manage this deferred data inside the view.

Any ideas?


Solution

  • You can use the list promise plugin to show a loading indicator while a Deferred is being resolved:

    var users = new Users.List();
    users.replace(Users.findAll());
    element.html(can.view('myView', { users: users });
    

    This will even allow you to show loading error messages:

    {{#if users.isPending}}
       <p>Loading, please wait...</p>
    {{else}}
      {{#if users.isResolved}}
       <ul>
          {{#each users}}
             <li>User {{ name }} {{ surname }}</li>
          {{/each}}
       </ul>
       {{else}}
       There was an error loading the user list.
       {{/if}}
    {{/if}}
    </ul>