Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
Access Alpine to create magic properties from standalone js file

I try to implement Alpine JS within a existing page.

For that, I'm using the CDN version of Alpine, which I'm loading within my <head>:

<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

Now I'm trying to access Alpine from a custom.js file, which is loaded automatically within the footer of my page:

Alpine.magic('post', function () {
    return function (url, data = {}) {
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            redirect: 'follow',
            body: JSON.stringify(data)
        });
    }
});

Within my content I tried this:

<div x-data>
    <h1>Alpine Test</h1>
    <button type="button" @click="$post('/api/users', { name: 'John Doe' })">Add user</button>
</div>

By clicking the button, this error occurs:

Uncaught ReferenceError: $post is not defined

I've also tried it with window.Alpine, without success.

How can I add magic properties and stuff like that without using modules?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When you use the defer attribute the browser executes the script after the document parsing. You have to add the defer attribute to the custom.js script as well, or embed the magic definition within an alpine:init event listener block:

document.addEventListener('alpine:init', () => {
    Alpine.magic('post', function () {
        return function (url, data = {}) {
            return fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                redirect: 'follow',
                body: JSON.stringify(data)
            });
        }
    });
})

This ensures that the magic definition happens only after the Alpine.js core is ready.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda