简体   繁体   English

通过Symfony 4中的ES6使用jQuery

[英]Using jQuery via ES6 in Symfony 4

I am building a fairly simple app using Symfony 4. I currently have Symfony loading Jquery and bootstrap and want to start to build my own triggers. 我正在使用Symfony 4构建一个相当简单的应用程序。我目前有Symfony加载Jquery和bootstrap,并希望开始构建自己的触发器。 So I've started to add my own bit of JS. 因此,我开始添加自己的JS。 Within this JS I need to detect if a certain button is clicked so my instinct is to use jQuery's on click function. 在此JS中,我需要检测是否单击了某个按钮,所以我的直觉是使用jQuery的on click函数。

I am having real trouble getting this working. 我真的很难让这个工作。 My additional code is being compiled by Webpack (via encore) but at no point does my event trigger, no matter what element I put it on. 我的其他代码正在由Webpack(通过encore)进行编译,但是无论我放置什么元素,事件都不会触发。 As far as I can see my additional Javascript functionality never gets called at all. 据我所知,我的其他Javascript功能根本不会被调用。

Any help appreciated. 任何帮助表示赞赏。 I'm by no means an ES6 expert so I may have something VERY wrong here. 我绝不是ES6专家,所以我在这里可能会出错。

assets/js/app.js 资产/ JS / app.js

import '../css/app.scss';
import $ from 'jquery';
import 'bootstrap';
import './checkLoan'; ## This is my file

app/js/checkLoan.js 应用程序/ JS / checkLoan.js

export default function() {
    console.log('i got loaded');
    $('#my-button').click(function (event) {
        event.preventDefault();
        console.log('I got clicked')
    });
};

Hey your click listener is never triggered because you import it but you never call the function. 嘿,您从未单击过单击侦听器,因为您将其导入但从未调用该函数。

You could create your listener functions in a separate file like listener.js : 您可以在单独的文件(例如listener.js)中创建监听器函数:

export default {
    clickListener(){
        console.log('i got loaded');
        $('#my-button').click(function (event) {
            event.preventDefault();
            console.log('I got clicked')
        });
    }
};

And the trigger the functions in your main app.js once the page has finished loading : 页面加载完成后,在主app.js中触发功能:

import $ from 'jquery';
import listeners from "./listeners"
$(document).ready(function () {
    listeners.clickListener();
    ...
});

EDIT: Also make sure the webpack.config.js file at the root of your project has the following line uncommented 编辑:还请确保您项目的根目录下的webpack.config.js文件的以下行未注释

.autoProvidejQuery()

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

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