gpt4 book ai didi

javascript - Ember.js: "this.$()"不适用于组件

转载 作者:行者123 更新时间:2023-12-01 02:44:13 25 4
gpt4 key购买 nike

方法 this.$() 不适用于组件。代码如下:

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.$());
},
});

在网络控制台上出现以下错误:

TypeError: this.$ is not a function

如何使用this.$()以及如何获取组件的 jQuery 元素?

环境:

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: -------------------------------

最佳答案

在组件方法中,this 并不代表组件本身,而是代表调用该方法的元素。

如果组件方法被另一个组件方法调用,例如 didRender(),则 this 是组件,而 this.$() code> 返回组件的 jQuery 元素。所以,这有效:

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.$());
},
});

如果组件方法由附加到 DOM 元素的某个事件调用,则 this 就是 DOM 元素,并且 this.$() 不起作用。必须使用 Ember.$(this) 来代替:

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));
},
});

关于javascript - Ember.js: "this.$()"不适用于组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47368614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com