I've got the following class in Javascript:
cart.js
class Cart{
static addItem(data, beforeSendCallback=null, successCallback=null, errorCallback=null) {
const emptyCallback = ()=>{}
if(data){
$.ajax({
url: '/orders/',
type: 'POST',
data: data,
beforeSend: beforeSendCallback == null ? emptyCallback : beforeSendCallback,
success: successCallback == null ? emptyCallback : successCallback,
error: errorCallback == null ? emptyCallback : errorCallback,
dataType: 'json'
})
}
}
}
Now, in a different file I've got:
item.js
...
function addItemToCart(e) {
e.preventDefault()
let data = {
'itemId': $('#item_id').val(),
'type': $('#item_type').val(),
'quantity': $('#quantity').val(),
'stock': $('#in_stock').val(),
'price': $('#item_price').val()
}
if (data.stock != 2) {
Cart.addItem(data, disableAddToCartBtn(true), disableAddToCartBtn(false))
}
}
...
When add-cart-btn
is pressed then this function is executed but I'm getting an error:
Uncaught ReferenceError: Cart is not defined, at HTMLAnchorElement.addItemToCart (item.js:20) at HTMLAnchorElement.dispatch (jquery.js:5206) at HTMLAnchorElement.elemData.handle (jquery.js:5014)
These two files are being added to app.js
which is in charge of processing them via webpack:
require('./core/cart')
require('./item')
Since I'm requiring ./core/cart
first I assumed its content would be available for ./item
, am I wrong?
You need to export the Cart
class in cart.js
, then import and actually assign it to a variable where you want to use it. In cart.js
:
// ....
module.exports = Cart;
Then in whatever module you want to use Cart
:
const Cart = require('./core/cart');
// use the `Cart` class.
Try assigning the imported cart to a variable:
const Cart = require('./core/cart');
and make sure you export the cart in cart.js:
module.exports = class Cart {
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.