Referencing classes and IDs in event callbacks


#1

Given code such as:

Template.myTemplate.events
  'click #some-button': (event) ->
    x = $('#other-thing').val()

This appears to work, but is it safe (as in, correct/future-proof)? Or do I need to do:

x = Template.instance().$('#other-thing').val()

#2

Sometimes I do:

'click #something': function (event, instance) {
  var foo = instance.find('#other-thing').value
}

future-proof? don’t count on it.


#3

I’d go with this:

Template.myTemplate.events
  'click #some-button': (event, instance) ->
    x = instance.$('#other-thing').val()

better scoping.


#4

What about accessing things within helpers? This doesn’t seem to work:

Template.page.helpers({
  loginStatus: function() {
    $el = Template.instance().$('#my-list');
    console.log($el);
  }
});

Chrome throws this error:

Error: Can’t use $ on template instance with no DOM


#5

You usually don’t want to access the DOM from a helper, because the DOM might still be under construction. You typically access the DOM from onRendered instead.


#6

Makes sense. It’s probably bad practice to be accessing the DOM from a helper, anyway.