kbascombe
kbascombe

Reputation: 87

Where does standard JS functions go in a Meteor application?

I've gone through tutorials for building web apps with Meteor and I'm still confused about where your standard JS function calls should sit so that they only get called once in the proper place.

For example I have the following two templates

<template name="list">
    <ul>
       {{> listItem}}
    </ul>
</template

and then ...

<template name="listItem">
    <li>Item</li>
</template>

If I then want to perform a DOM manipulation over each li tag where do I put the JS and what Meteor 'thing' (sorry not sure of the correct term) does it take?

Should it be in list.js or in listItem.js? I only need it to run once so I would have thought list.js but technically the JS is applying to the listItem template.

Should it be inside the Meteor.template.rendered thing or the Meteor.template.created thing? Is there another thing it should use or should it not be inside anything?

Sorry if this is a bit confusing, I basically want to know which file this code would sit in and how to use it so that it only runs onces.

Any help is much appreciated, thanks!

Upvotes: 0

Views: 150

Answers (1)

emgee
emgee

Reputation: 1234

If you want to execute a Javascript function on each <li> after it's rendered, I think it's most logical to have the code in listItem.js.

In order to have your code executed "once", put it in Template.listItem.rendered = function () { ... }; as per the Meteor docs.

I have once in scare quotes because it won't only be once, it'll fire every time that template is re-rendered, which may or may not be what you want. As you note there's also Template.listItem.created = ... Without a bit more information (is your <ul> going to be bound to a reactive data source, or is it static, etc.?) , I can't give you better advice.

Upvotes: 1

Related Questions