javascript - Backbone template loading using promises -


similar this question, i'm looking way load templates via javascript promises. issue i'm running returning compiled template backbone view. note: this.getfile() returns new promise, fetches template expected.

template: function(attributes) {   this.getfile('/path/to/template').then(function(tpl) {     var compiled = handlebars.compile(tpl);     return compiled(attributes);   }, function(error) {     console.error('failed!', error);   }); } 

within view's initialize, have listener set to

initialize: function() {   this.model.on('change', this.render, this); } 

which triggers expected when data fetched server.

the problem when render function executes line

render: function() {   ...   this.$el.html(this.template(attributes));   ... } 

nothing renders html expect. i'm sure i'm missing simple within template promise callback, no matter change, html not render , no errors appear.

like @muistooshort have pointed out. template function not return anything, async call function , deal it.

however, render function syncronous, execute template function, add whatever returned directly $el. in case, there nothing add.

there 2 solutions problem. 1. make template function return promise. , in render, wait template finish before adding stuff $el.

example:

template: function(attributes) {     return this.getfile('/path/to/template').then(function(tpl) {         var compiled = handlebars.compile(tpl);         return compiled(attributes);     }); } 

note return this.getfile..., return promise, resolve value compiled(attributes).

then render function be:

render: function() {     var self=this;     this.template(attributes).then(function(data){         self.$el.html(data);// data stuff compiled.     }) } 

however, may suggest different solution in how manage templates?

as personal opinion, templates, either ejs, jade, or hbs, small when compiled. these data compiled in js files using require. use jstemplate file

module.exports={     t1:require(path/to/template1),     t2:require(path/to/template2), } 

then, in other backbone view js files.

var alltemplates=require('./jstemplate.js'); ... render:function(){     this.$el.html(alltemplates.t1(attributes)); } 

this in opinion easier handle, , faster in client side, because don't have file in client.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -