Creating a Dust.js Template Using Backbone.LayoutManager

Let me elaborate on my setup: I have pre-compiled dust.js templates that I would like to use with Backbone.LayoutManager.

Backbone.LayoutManager uses the following configuration:

Backbone.LayoutManager.configure manage: true fetch: (name) -> name 

So the template name is passed through the selection for rendering, and I would like to override the rendering as follows:

 render: (template, context) -> done = @async dust.render @template, context, (err, out) -> throw err if err done(out) 

But I can’t do this using rendering (presumably because the author of LayoutManager suggested that the rendering of the template will be synchronized).

Does anyone know how I can do this?

+4
source share
1 answer

You will need to modify the LayoutManger to handle the asynchronous display of templates.

One way to do this is to use the jQuery Deferred object, in which the call to render returns an instance of the Deferred object, which is then resolved when the Dust library is called.

Then modify Backbone.LayoutManager to NOT continue to do what it wants with the templates until this Pending object is resolved.

in render :

 render: (template, context) -> dfd = $.Deferred() dust.render @template, context, (err, out) -> throw err if err done(out) dfd.resolve() return dfd; 

Then you take the method in Backbone.LayoutManager that calls the rendering and instead of doing something with the return from the rendering, you attach this β€œsomething” to the done handler for the deferred that you passed back.

  dfd = render(template, context) dfd.done(do_something_with_this_template); 

I use Marionette.js (along with the asynchronous option) and dust, this is what my main render method looks like:

  render: function(){ var dfd = $.Deferred(); var template_context = this.model; if(_.isUndefined(template_context) || _.isFunction(template_context)){ template_context = new (Backbone.Model.extend({})); } if(this.id) this.$el.attr('id', this.id); var that = this; dust.stream(this.tpl_name, template_context.toJSON()) .on('data', function(data){ that.$el.html(data); }) .on('end', function(){ dfd.resolve(); that.enable_menus(); that.trigger('template:rendered'); }) .on('error', function(err){ dfd.reject(); window.le(err.message, err); that.trigger('template:error'); }); return dfd; } 

(Obviously not using coffeescript either ...)

+4
source

Source: https://habr.com/ru/post/1436060/


All Articles