简体   繁体   English

我如何在 Shopware 6 Storefront 中监听和响应 JavaScript 事件

[英]How Do I Listen To And React To JavaScript Events In Shopware 6 Storefront

I am building a Shopware 6 JavaScript plugin for the storefront.我正在为店面构建一个 Shopware 6 JavaScript 插件。 I created a button and need to listen to it and react accordingly when it is 'Clicked'.我创建了一个按钮,需要收听它并在它被“点击”时做出相应的反应。

Below is my code which does not seem to work.下面是我的代码,它似乎不起作用。

main.js file code below main.js 文件代码如下

//Resources\app\storefront\src\main.js

import TestClickPlugin from './testclick/testclick.plugin';

const PluginManager = window.PluginManager;
PluginManager.register('TestClickPlugin', TestClickPlugin, '.swp');

plugin file code below插件文件代码如下

//Resources\app\storefront\src\testclick\testclick.plugin.js
import Plugin from 'src/plugin-system/plugin.class';

export default class TemporaryWatermarkPlugin extends Plugin {

    init() {

       document.querySelector(".swp").addEventListener("click",  this.logThis().bind(this));       
    }

    logThis() {
        console.log("It Works!!!!!");     
    }
   
}

And lastly, my twig file code below最后,下面是我的树枝文件代码

//Resources\views\storefront\page\product-detail\buy-widget.html.twig

{% sw_extends '@Storefront/storefront/page/product-detail/buy-widget.html.twig' %}

    {% block page_product_detail_buy_inner %}

        {{ parent() }}


            {% block swp_block %}

                <div>
                   <button class="swp">Click Me </button>
                </div>

            {% endblock %}

    {% endblock %}

How do I get the function logThis() to run when clicked in the storefront.在店面中单击时,如何让函数logThis()运行。

Change改变

this.logThis().bind(this)

to

this.logThis.bind(this)

since you want to reference the function, not call it.因为你想引用函数,而不是调用它。

Also in the init function you may want to use this.el instead of document.querySelector(".swp") since you already registered the plugin for that element.同样在init函数中,您可能希望使用this.el而不是document.querySelector(".swp") ,因为您已经为该元素注册了插件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM