简体   繁体   中英

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. So I've started to add my own bit of 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.

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. As far as I can see my additional Javascript functionality never gets called at all.

Any help appreciated. I'm by no means an ES6 expert so I may have something VERY wrong here.

assets/js/app.js

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

app/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 :

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 :

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

.autoProvidejQuery()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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