Last Updated: May 01, 2021
·
2.709K
· codefendant

Cleaning up meteor.js template related code

I really love meteor.js, as a result I have been writing a lot of code using recently. Up until now it has bothered me that when writing template related code to register handlebar helpers and passing in the events hash, I was repeating the code "Template.templateName". I've started using underscores extend function to neaten it up a bit...

Instead of:

Template.project_list.projects = ->
  Projects.find({})

Template.project_list.display = (data, options)->
  options.fn @ unless Session.get("current_project_id")?

Template.project_list.events
  "click .project": (event)->
    projectID = $(event.target).data("project-id")
    Session.set("current_project_id", projectID)

  "click .project .btn-destory": (event)->
    projectID = Session.get("current_project_id")
    Projects.remove(projectID)

You could use the extend function to write this a lot more neatly:

_.extend Template.project_list,
  projects: ->
    Projects.find({})

  display: (data, options)->
    options.fn @ unless Session.get("current_project_id")?

  events:
    "click .project": (event)->
      projectID = $(event.target).data("project-id")
      Session.set("current_project_id", projectID)

    "click .project .btn-destory": (event)->
      projectID = Session.get("current_project_id")
      Projects.remove(projectID)

You could go a step further and extend the Template object itself, grouping all template related code together.

Small change, but a big impact on the overall readability. Especially when you start adding more and more templates.

Let me know if you have any other tips for DRYing up your meteor code.

2 Responses
Add your response

I just split the events, helpers and additional functionality into separate folders, this way I always know where to look for it :)

over 1 year ago ·

Thank you very much for the tip!!

over 1 year ago ·