Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping meteor.js handlebars templates in coffeescript classes

I'm totally digging on meteor, but I'm stuck trying to cut down on the global-ness of the examples and add a dash of OOP.

Currently, my code looks like this:

# View for Search Form
form = Template.SearchForm  
form.events =
  'submit #search_form' : query_submitted
  'click #load_more' : -> Songs.get_next_page()
  'focus #query' : clear_query_field

form.page = -> Songs.page
form.total_pages = -> Songs.total_pages 

But, a la spine or backbone, what I'd really like to have is something like this:

class SearchForm extends Template.SearchForm
  events:
    'submit #search_form' : query_submitted
    'click #load_more' : -> Songs.get_next_page()
    'focus #query' : clear_query_field


  page : -> Songs.page
  total_pages : -> Songs.page

  # etc etc

form = new SearchForm

What's the right way to wrap a handlebars template in meteor?

I've managed to wrap Meteor.Collection, but because handlebars names the object after the template, I'm not sure the right way to do it for the Template.

UPDATED

@greg pointed out that you can use _.extend to add the properties. That works, but what if I want to fold the event handler methods 'query_submitted' and 'clear_query_field' into the class? Something like this:

_.extend Template.SearchForm,
  events :
    'submit #search_form' : @query_submitted
    'click #load_more' : -> Songs.get_next_page()
    'focus #query' : @clear_query_field

  page : -> Songs.page
  total_pages : -> Songs.total_pages

  clear_query_field : (event) ->
    console.log 'focus'

  query_submitted : (event) ->
    event.preventDefault()
    Songs.clear()
    Songs.query = $('#query')[0].value 
    Songs.search()

Doesn't quite work. The event handlers aren't being called properly and I get errors in the console like:

Uncaught TypeError: Object [object Window] has no method 'query_submitted'

Similarly,

events :
    'submit #search_form' : (e) -> @query_submitted(e)

Gives:

Uncaught TypeError: Cannot call method 'call' of undefined

So what's missing?

like image 950
Scott Simon Avatar asked May 17 '12 17:05

Scott Simon


2 Answers

Meteor comes with underscore so you could:

_.extend Template.SearchForm,
  events:
    'submit #search_form' : query_submitted
    'click #load_more' : -> Songs.get_next_page()
    'focus #query' : clear_query_field

  page: -> Songs.page

  total_pages: -> Songs.page
like image 73
greggreg Avatar answered Oct 21 '22 19:10

greggreg


Have you tried replacing @ with Template.Searchform. in your event bindings?

like image 35
aceofspades Avatar answered Oct 21 '22 21:10

aceofspades