Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function is not defined with Laravel Mix

First , code in resources/js/app.js

function button1Clicked(){
  console.log('Button 1 is clicked');
}

Second , code in testing.blade.php

<!DOCTYPE html>
<html>
<head>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Testing</title>
</head>
<body>
  <button onclick="button1Clicked()">Button 1</button>
  <button onclick="button2Clicked()">Button 2</button>

  <script type="text/javascript" src="{!! asset('js/app.js') !!}"></script>
  <script type="text/javascript">
    function button2Clicked(){
      console.log('Button 2 is clicked');
    }
  </script>
</body>
</html>

After npm run dev and testing in localhost

enter image description here

As a result, JavaScript function button1Clicked() in resources/js/app.js is not defined. but the function button2Clicked() in testing.blade.php can be defined. Is it a bug from Laravel Mix or I did some mistakes

like image 891
YChen Avatar asked Oct 09 '17 09:10

YChen


2 Answers

I had the same problem as you.

It turned out that when Laravel-mix, aka Webpack, compile the js, it wraps our function in a closure.

For example, when we define a function like this

function setlocale(code) {
     console.log(code);
}

Webpack will generate into

(function(module, exports, __webpack_require__) {

     function setlocale(code) {
         console.log(code);
     }

});

That's why we can access the variables or functions inside that closure, but we cannot from the outside as it limits our scope.

A simple solution is setting our function into window variable, which is a global variable.

window.setlocale = function (code) {
    console.log(code);
}
like image 148
Quinn Wynn Avatar answered Nov 19 '22 02:11

Quinn Wynn


update the code in resources/js/app.js as below-

button1Clicked = function(){
    console.log('Button 1 is clicked');
};

then it will be available for global scope.

like image 7
Ranjan Fadia Avatar answered Nov 19 '22 01:11

Ranjan Fadia