QBCore in depth: the player and their money · Lesson 3/4 · 9 min
QBCore callbacks: requesting data from the server
When the client needs an answer from the server (do I have a balance? what items do I have?), you use a callback.
A normal event is one-way (the client notifies the server). But sometimes the client needs a RESPONSE: "do I have enough money for this?". That's what QBCore callbacks are for.
On the server: register the callback
QBCore.Functions.CreateCallback('tienda:comprar', function(source, cb, precio)
local Player = QBCore.Functions.GetPlayer(source)
if not Player then return cb(false) end
if Player.Functions.RemoveMoney('cash', precio, 'compra') then
cb(true) -- respond to the client: purchase OK
else
cb(false) -- no money
end
end)server.lua
On the client: call it and wait for the response
QBCore.Functions.TriggerCallback('tienda:comprar', function(exito)
if exito then
print('Purchase completed')
else
print('You don\'t have enough money')
end
end, 1500) -- 1500 = price passed to the serverclient.lua
The decision (do they have money?) and the charge happen on the SERVER. The client only receives yes/no. That way no cheating is possible. And like in ESX: call cb() on ALL paths, or the client hangs.
Practice what you learned
0/3¿Cuándo necesitas un callback de QBCore en lugar de un evento normal?
Completa el registro del callback de servidor que responde sí/no.
QBCore.Functions.('tienda:comprar', function(source, cb, precio) local Player = QBCore.Functions.GetPlayer(source) if not Player then return cb(false) end cb(true)end)Pista
En el servidor se registra; en el cliente se dispara con TriggerCallback.
Ordena la llamada del cliente que pide la compra al servidor y reacciona a la respuesta.
Coloca las líneas en el orden correcto con las flechas.
print('Compra realizada')QBCore.Functions.TriggerCallback('tienda:comprar', function(exito) endend, 1500) else print('No tienes suficiente dinero') if exito thenPista
TriggerCallback recibe el nombre, la función que maneja la respuesta y, al final, los argumentos (el precio 1500).
Challenge: code it yourself
Create a callback that returns true only if the player has the 'police' job.
Write it yourself in your editor (VS Code) and test it on your server. You learn here by doing it, not by copying.
See hint
Compare Player.PlayerData.job.name == 'police' and respond with cb(true/false).
Escribe aquí tu solución:
