Shanthakumar
Shanthakumar

Reputation: 768

How to update view after Ember.Handlebars.compile?

I'm using emberJS (without Rails) and have templates in different files in templates/*.hbs

I used ajax to query them and compile templates.

    App.SetupTemplate = function(name) {              
            $.ajax( {url:"templates/"+name+".hbs", success: function(response) { 
            Ember.TEMPLATES[name] = Ember.Handlebars.compile(response);          
    } });                                                                        
    };                                                                           


    App.ProfileRoute = Ember.Route.extend({                                      
            setupController: function(controller) { App.SetupTemplate('profile'); 
    },                                                                           
    });         

If I hit ProfileRoute it compiles the template but not updated automatically in view. But it works for the later clicks on same route as template is already compiled and view is rendered properly. I don't know how to use transitionTo to the same route which will make it happen.

What should I do to automatically update view on first click itself ?

-Thanks.

Upvotes: 1

Views: 318

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

You'd need to block the transition until the template has actually been downloaded

App.needsTemplate = function(name){
  return Ember.isEmpty(Ember.TEMPLATES[name]);
};
App.setupTemplate = function(name) {  
    return new Ember.RSVP.Promise(function(resolve, reject){

      if(!App.needsTemplate(name)){
        resolve();
      }   else {
        $.ajax( {url:"templates/"+name+".hbs"}).then(function(response){
            Ember.TEMPLATES[name] = Ember.Handlebars.compile(response);

            resolve();
         });
      }                                                                                           
    });
};


App.IndexRoute = Ember.Route.extend({
  model: function() {
    return ['red', 'yellow', 'blue'];
  },
  afterModel: function(model, transition){
    if(App.needsTemplate('index')){
      transition.abort();
      App.setupTemplate('index').then(function(){
        transition.retry();
      }); 
    } 
  }
});

http://emberjs.jsbin.com/OxIDiVU/340/edit

Upvotes: 1

Related Questions