【发布时间】:2019-03-12 02:39:12
【问题描述】:
在 Ember 组件属性中存储一个普通 JS 节点列表,但是当尝试使用 this.prop 或 this.get('prop') 或 get(this, 'prop') 在函数中访问它时,它只返回 undefined .
我有 console.log(this.prop) 并且我得到了 NodeList。仅从 didRender() 钩子中的函数中检索它不会返回 NodeList。
我一定遗漏了一些明显的东西,比如我需要先把它变成一个 Ember 对象?
我的步骤:
1.在Ember组件中didRender()钩子
2. 使用纯JS 使用querySelectorAll('.my-class') -> 返回一个NodeList // working!
3.在Nodelist中添加事件监听// working!
4.设置组件属性为NodeList值this.set('prop', Nodelist)// working!
5.在didRender()外调用事件监听函数// working!
6. 在函数中(didRender() 钩子外),尝试使用this.prop、this.get('prop') 或get(this, 'prop') 检索变量并分配给变量。 // NOT working!
import Component from '@ember/component';
import { get, set } from '@ember/object';
export default Component.extend({
myProp: null,
handlerForButtons(e){ // Fires when any button clicked. Handler for buttons.
e.preventDefault();
let currentButton = e.target;
currentButton.style.display = 'none';
let currentSibling = currentButton.nextElementSibling;
currentSibling.style.display = 'block';
// this assignment myProp is undefined
let myProp = this.myProp; // also this.get('myProp'); or get(this, 'myProp'); not working.
console.log("myProp: ", myProp);
},
didRender(){
let allButtons = document.querySelectorAll('ul.aog-list li > button');
this.addListeners(allButtons, ['click', 'keydown'], this.handlerForButtons);
let allSiblings = document.querySelectorAll('ul.aog-list .aog-wrap');
this.set('myProp', allSiblings);
console.log("SET myProp: ", this.myProp); // Shows a NodeList of 32 items
allSiblings.forEach(function(e){
e.style.display = 'none'; //Hide sibling divs for initial state
});
}
}
【问题讨论】:
-
请出示您的代码!可能你在某处丢失了
this-context。 -
您可以添加您的模板吗?如何调用操作可以更改
this以及 -
显然问题是你如何调用 handlerForButtons
-
谢谢各位。我将以一种更具声明性的方式(更像 Ember 方式)来尝试这个,看看这是否会让事情变得更简单。
标签: ember.js