Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting element by ID in Ember

I am running two ember applications. One has the following component:

import Ember from 'ember';

export default Ember.Component.extend({
 tagName: 'a',

 click: function() {
  Ember.$('#wrapper').toggleClass('toggled');
 }
});

and the other one, has this one:

import Ember from 'ember';

export default Ember.Component.extend({
 tagName: 'a',

 click: function() {
  this.$('#wrapper').toggleClass('toggled');
 }
});

What I can't understand here is why in one application I select an element by ID using Ember.$('#wrapper') and in the other using this.$('#wrapper').

What is this about? Ember version?

UPDATE

I'm very puzzled, since both components are the same:

{{#show-menu}}
    <i class="fa fa-bars"></i>`
{{/show-menu}}`

They are both hamburger menus used to hide a sidebar div, and the #wrapper is an external element.

Since in both cases the #wrapper are external elements, shouldn't just the first case work @Gaurav and @Kevin Jhangiani?

like image 482
Marcelo Borges Avatar asked Nov 16 '15 19:11

Marcelo Borges


1 Answers

The difference is in the context of the jquery selector.

Ember.$()

is scoped to the entire document, ie, you can access any element on the page.

In contrast,

this.$()

is scoped to the current component or view, and thus you can only access dom elements that are children.

Generally, you should be using this.$ as it will be more performant (since the search space is only child elements). Ember.$ should be reserved for times when you absolutely need to access an element outside of the current context.

like image 153
Kevin Jhangiani Avatar answered Oct 11 '22 14:10

Kevin Jhangiani