Client JavaScript in Templates
-
Please advice. How to use client JavaScript in themes?
My case: forpost.tpl
for every user, I would like to call JavaScript function. I can't create necessary elements in template on server, additional work should be done on client. I'm looking for the best option for NodeBB. If you have several approaches, please share themThanks.
-
Solution
I hope, there are more possible solutions, but I have resolved it with a help of my custom theme.
I have subscribed toaction:posts.loaded
andaction:topic.loading
, and I did much jQuery (selectors, like[component="something"]
)But, I would like more
define
from requirejs with name just for posts... -
let's say you have a template
path/to/template.tpl
this is how the JS file using require.js should look like:
define('forum/path/to/template', [], function() { var script = {}; script.init = function() { }; // this gets called when the route is loaded return script; });
hopefully that helps
-
@psychobunny Thanks. Yep, I have found myself this approach, after several tries.
I'm asking about case, what to do when you want to add additional logic to existed route? For example toforum/topic
?
Seems It could be done only by custom theme + actions/filters... -
There's a few ways of doing it, like this:
https://github.com/NodeBB/nodebb-plugin-friends/blob/master/public/scripts/client.js#L9-L10
-
@psychobunny nice, It's very helpful.