灰烬this.get()没有检索组件上的属性

时间:2018-10-07 02:59:23

标签: ember.js

在Ember组件属性中存储一个普通JS NodeList,但是当尝试使用this.prop或this.get('prop')或get(this,'prop')在函数中访问它时,它仅返回未定义的。

我有console.log(this.prop)并得到了NodeList。只是从didRender()挂钩内的函数中检索它不会返回NodeList。

我肯定想念一些明显的东西,比如我需要先把它变成一个Ember对象?

我的步骤:
1.在Ember组件didRender()挂钩中
2.使用querySelectorAll('.my-class')->使用普通JS->返回NodeList // working!
3.将事件侦听器添加到节点列表// working!
4.将组件属性设置为NodeList值this.set('prop', Nodelist) // working!
5.在didRender()钩子// working!之外调用事件监听器函数
6.在函数中(在didRender()钩外),尝试使用this.propthis.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
        });

    }
}

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

1 个答案:

答案 0 :(得分:0)

当我亲自重写此代码时,您需要访问组件的实际元素以添加侦听器:this.element.addEventListener而不是this.addEventListener

但是您确实应该重写此代码以使其更加方便,并使用操作来处理click事件,因为这样可以避免所有这些问题。