Question

I need to load part of my html template, just after I get the result from templateHelper that using ajax.

In my ItemView code:

templateHelpers: {
  currentUserCan:  function(action) {
    $.when( currentUser.can(action) ).done(function(permission){
      return permission;
    });
  }
}

can function:

can: function( action ){

 var defer = $.Deferred(),
 params = { .... }

 $.get( config[ 'api' ] , params)
 .done(function(response) {
    defer.resolve(response['permission'])
  })
 .fail(function(response){
    defer.resolve(false) 
  });

  return defer.promise();
}

My template:

<div class="large-8 columns">
  <p><% if (currentUserCan('some_action')) {  do something, console.log("can") } else { console.log('can not')}%></p>
  <p>Last Status:<%= date %></p>
</div>

<div class="large-8 columns">
...
...

Because of the async ajax, I'm getting undefined as result, and 'can not' at console, although it got true. How can I load my code at the if statement, only after the ajax is completed?

Était-ce utile?

La solution

Don't try to use asynchronous code in a "synchronous way".

Maybe, it will be a good solution for you:

templateHelpers: {
  currentUserCan:  function(action) { return currentUser.can(action); }
}
  • here we return promise from the function, since we want to react on asynchronous action completion.

<div class="large-8 columns"> <p><% $.when(currentUserCan('some_action')).done(function(permission) { if(permission) console.log("can"); else console.log('can not'); }) %></p> <p>Last Status:<%= date %></p> </div>

  • here we use promise right from the template.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top