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 has the following:

 import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'a', click: function() { this.$('#wrapper').toggleClass('toggled'); } }); 

I can’t understand why in one application I select an element by identifier using Ember.$('#wrapper') , and in another this.$('#wrapper') .

What is it? Amber version?

UPDATE

I am very puzzled since both components are the same:

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

They are a hamburger menu that hides the sidebar of a div, and #wrapper is an external element.

Since in both cases #wrapper are external elements, should not only the first case of @Gaurav and @Kevin Jhangiani work?

+6
source share
3 answers

The difference lies in the context of the jquery selector.

 Ember.$() 

attached to the entire document, i.e. You can access any item on the page.

On the contrary

 this.$() 

tied to the current component or view, and so you can only access dom elements that are children.

Generally, you should use this.$ As it will be more efficient (since the search space is only children). Ember.$ Should be reserved for cases when you absolutely need access to an element outside the current context.

+11
source

Ember.$('#wrapper') will find the element on the page with the wrapper id.

this.$('#wrapper') will find the elution inside the component with the wrapper identifier.

If it is likely that the component that you define will ever occur more than once on a page, then you should not use either one. Edit the appropriate template so that wrapper a class, not an identifier. Then use:

this.$('.wrapper')

+6
source

Since you, in fact, just switch the class, especially the "Ember" way to do this has a conditional class on your wrapper and switches the property to your component:

import Ember from 'ember';

 export default Ember.Component.extend({ tagName: 'a', classToggle: false, click: function() { this.toggleProperty('classToggle'); } }); 

Then on your DOM element, you can have a conditional class:

 <div id="wrapper" class="{{if toggleClass "toggled"}}">...</div> 

or if you are using an older version of Ember:

 <div id="wrapper" {{bind-attr class="toggleClass:toggled"}}>...</div> 

This is a bit more reusable since your component does not rely on the DOM element (which can become messy if you want to reuse this component at some time).

+1
source

All Articles