Using Handlebars.js helpers to create active elements with jQuery?

假装没事ソ 提交于 2019-12-12 08:33:45

问题


Is it possible to within a Handlebars.js helper to create elements using jQuery and attach event handler to them? I'd like to be able to create active elements using helpers.

Example:

Handlebars.registerHelper("button", function(title) {
    var button = $('<button>').text(title);
    button.click(function() {
        alert("Button " + title + " clicked.");
    });
    return $('<div>').append(button).html();
});

In the handlebars template I instantiate the button like this:

{{{button "Click Me!"}}}

I understand that this can not work, since the jQuery's html() function `removes' the event handler... but simply returning button obviously does not work either. Handlebars helpers should be able to return DOM nodes, but this is not possible, right? I tried to return button.get(), but without success.

Any ideas?


回答1:


What you could do is create a function outside of registerHelper to be called onClick. So the code for that would look like this:

Handlebars.registerHelper("button", function (text) {
    var button = $('<button></button>').text(text).attr('onclick', 'button_clickEvent()');
    return $('<div></div>').append(button).html();
});

var button_clickEvent = function () {
    alert("Button " + $(this).text() + " clicked.");
};



回答2:


Now that MutationObserver is more supported and webcomponents-lite is an acceptable polyfill for it, you can use that to get a hold of elements created from Handlebars templates. See my answer to a more recent question about the same thing.



来源:https://stackoverflow.com/questions/8019810/using-handlebars-js-helpers-to-create-active-elements-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!