how to bind mouseover, click events on element inside jsrender template-Collection of common programming errors
{{:#data}}
renders #data as a string, so that approach won’t work unless #data stringifies and parses neatly. Objects won’t stringify or parse neatly without manual JSON usage. In fact, I suspect only numbers, booleans, undefined
, and null
will stringify and parse correctly. That approach also won’t work if the function is not global. Being forced to define the callback function globally any time you want to do this strikes me as a severe problem. So I can’t recommend using in-tag event-handlers, especially when you already have JavaScript running.
Instead, after you insert your rendered content into the DOM, you can bind the event there. Here’s a rough sketch.
Add a class or some other selector-fodder to your
Put each of your #data values into an object using an equivalent of
liv_{{:nid}}
as the key.
var dataMap = {};
$.each(yourDataValues, function (i, value) {
dataMap['liv_' + value.nid] = value;
});
Lastly, bind a live event to the container into which you pushed your rendered template.
$(containerOfRenderedTemplate).on('mouseenter', '.onMouseEnter', function () {
var id = $(this).attr('id');
var data = dataMap[id];
desiredCallbackFunctionWhichConsumesData(data);
});
dataMap
and the event-binding call should be within the same scope.
Note: If this rendering can happen more than once, and you need to replace the rendered content with all-new rendered content, you should unbind the old event before binding the new one.
$(containerOfRenderedTemplate).off('mouseenter', '.onMouseEnter');