Reputation: 65
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?
Upvotes: 6
Views: 1238
Reputation: 7586
Have you tried replacing @ with Template.Searchform. in your event bindings?
Upvotes: 1
Reputation: 12085
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
Upvotes: 2