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.
Written by Che
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#