Return html object from helper helper

I need to send an html object from handlebars helper like this:

Handlebars.registerHelper('helper', function () { //Create an input object var inp=$('<input type="text" name="name">'); //How to return 'inp' object without using Handlebars.SafeString return inp; }); 

I understand that I can return the html string using "Handlebars.SafeString (), but this is not useful to me. I need to pass an html object with the purpose of some event.

Is it possible?

+3
javascript jquery handlebarshelper registerhelper
source share
1 answer

As the dandavis commented using Handlebars, you cannot create template objects, but only strings. However, you can get the elements after they have been added to the DOM using MutationObserver. I created some helpers that do just that, see the jq in post-render-bars . See also this answer to a similar question for a different approach.

Here's a demo for post-render-bar columns, check out the example under the heading "Define jQuery element in template".

The helper uses MutationObserver , here is browser support , see webcomponents-lite for polyfill if necessary.

A brief description of the relevant code:

watch.js defines a function forHtml(html, callback) that triggers a callback when a given html is encountered in the DOM. It modifies html to temporarily have a class that makes it unique.

jQueryHelpers.js defines an auxiliary jq . The helper uses the watch.forHtml function to observe the block defined by the helper, and calls the function you passed to the template, with the jquery element as an argument.

Here's a shortened version of the example I'm linked to, template:

 <p>button with a handler: {{#jq setHandler}}<button>try me</button>{{/jq}}</p> 

And js:

 var context = { setHandler: function(element) { element.on('click', function() { alert('clicked'); }); } }; var html = template(context); // append html somewhere and the setHandler will be invoked 
+3
source share

All Articles