加载后触发的类方法,之后不工作

时间:2018-01-02 13:54:29

标签: javascript ecmascript-6

我正在使用Webpack和Babel将项目移动到ES6来编译代码。这就是我现在所拥有的:

entry.js

import Header from './components/header';

(function() {
  const header = new Header();
})();

header.js

export default class Header {
  constructor() {
    this.bodyTag = document.querySelector('body');
    this.toggleNavigationButton = document.querySelector('#toggleNavigationButton');

    this.toggleNavigationButton.addEventListener('click', this.toggleMobileNavigation());
  }

  toggleMobileNavigation() {
    this.bodyTag.classList.toggle('CLICK');
  }
}

webpack.config.js

module.exports = {
  entry: "./js/entry.js",
  output: {
      filename: "./js/bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      },
      {
        test: /\.scss$/,
        use: [
          { loader: "style-loader" },
          { loader: "css-loader" },
          { loader: "sass-loader" }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
};

问题是,当页面加载时,方法toggleMobileNavigation被触发,click事件根本不起作用。

我错过了什么?

1 个答案:

答案 0 :(得分:2)

这是因为你的回调有括号,然后立即调用,尝试删除它们:

 this.toggleNavigationButton.addEventListener('click', this.toggleMobileNavigation);