Method this.$()
is not working on a component. Following code:
app/components/example-component.js:
import Ember from 'ember';
export default Ember.Component.extend({
didRender() {
Ember.$('body').click(this.exampleMethod).click();
},
exampleMethod() {
console.log('"this" on exampleMethod():');
console.log(this.$());
},
});
Gets following error on web console:
TypeError: this.$ is not a function
How is this.$()
to be used and how to get the jQuery element of a component?
Environment:
DEBUG: -------------------------------
DEBUG: Ember : 2.13.0
DEBUG: Ember Data : 2.13.1
DEBUG: jQuery : 3.2.1
DEBUG: Ember Simple Auth : 1.3.0
DEBUG: -------------------------------
In a component method this
doesn't represent the component itself, but the element that has called the method.
If the component method is called by another component method, like didRender()
, then this
is the component, and this.$()
returns the jQuery element of the component. So, this works:
app/components/example-component.js:
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
exampleAction() {
console.log('"this" on exampleAction():');
console.log(this.$());
},
},
didRender() {
this.send('exampleAction');
console.log('"this" on didRender():');
console.log(this.$());
this.exampleMethod();
},
exampleMethod() {
console.log('"this" on exampleMethod():');
console.log(this.$());
},
});
If the component method is called by some event attached to a DOM element, then this
is the DOM element, and this.$()
doesn't work. Ember.$(this)
must be used instead:
app/components/example-component.js:
import Ember from 'ember';
export default Ember.Component.extend({
didRender() {
console.log('"this" on didRender():');
console.log(this.$());
Ember.$('body').click(this.exampleMethod).click();
},
exampleMethod() {
console.log('"this" on exampleMethod():');
// console.log(this.$()); This doesn't work
console.log(Ember.$(this));
},
});