使用Meteor+iron:router时,为何需在router文件导入集合?
lib/routes.js (Even If You Imported It in Template JS) Great question—this boils down to Meteor's file loading priority and how iron:router interacts with template rendering and collection registration. Let's break it down step by step:
1. Meteor's File Loading Order Rules
Meteor has a strict loading sequence for files outside the imports/ directory, and lib/ is one of the earliest directories to load. Here's the critical detail:
- Files in
lib/load before files in other directories (likeclient/or yourimports/ui/template files). importstatements inimports/files only resolve when the parent file is loaded. So if your template's JS file (inimports/ui/) loads afterlib/routes.js, the collection import inside it hasn't run yet when the router sets up your routes.
2. Collection Registration in Meteor
Mongo Collections in Meteor need to be instantiated and "registered" before they can be accessed in templates. If you only import the collection in your template's JS file:
- When
iron:routerparses your route configuration (inlib/routes.js), it prepares the template for rendering—but the collection hasn't been instantiated yet (since the template JS file hasn't loaded). - Templates rely on having access to the collection instance when they initialize. If the collection isn't already registered at that point, the template can't find it.
3. How iron:router Amplifies This
iron:router doesn't just map URLs to templates—it pre-processes template dependencies when routes are defined. If your route references a template that depends on a collection, the router expects that collection to exist already. By importing the collection in lib/routes.js, you ensure it's instantiated before the router sets up the route and prepares the template.
Recommended Fixes
To avoid duplicate imports and keep your code clean:
- Create a centralized collection file, e.g.,
imports/api/reservations/collection.js, where you export yourReservationscollection instance. - Import this collection file in a top-level initialization file (like
lib/init.js) that loads early, or directly in bothlib/routes.jsand your template JS files. This guarantees the collection is registered before any code that needs it runs. - Avoid relying on global collection variables (they work but aren't ideal for modular Meteor apps). Stick to explicit imports to keep your code maintainable.
内容的提问来源于stack exchange,提问作者bonsai

