Skip to content

Instantly share code, notes, and snippets.

@pimlie
Created April 25, 2020 12:53
Show Gist options
  • Save pimlie/b31201031635d185a2fbe5aa986fedef to your computer and use it in GitHub Desktop.
Save pimlie/b31201031635d185a2fbe5aa986fedef to your computer and use it in GitHub Desktop.
nuxt-proxy-hooks.js
window.process = { client: true, server: false }
// definition of hooks that exists
nuxtHooks = {}
function addHook(n, h) {
nuxtHooks[n] = nuxtHooks[n] || []
nuxtHooks[n].push(h)
}
function callHook(n, thisArg, argList) {
if (!nuxtHooks[n]) {
return
}
nuxtHooks[n].forEach(h => h.apply(thisArg, argList))
}
// prevent errors
stubProxy = new Proxy({}, {
get: () => () => {}
})
$nuxt = new Proxy({}, {
get(t, n) {
if (n === 'client') {
return window.process.client ? $nuxt : stubProxy
}
if (n === 'server') {
return window.process.server ? $nuxt : stubProxy
}
return new Proxy(addHook, {
get(ct, cn) {
if (cn === 'call') {
return function () {
return callHook(n, this, arguments)
}
}
},
apply: (t, thisArg, argList) => addHook(n, ...argList)
})
}
})
$nuxt.created(function (type) { console.log('Nuxt Created: ' + type, this) })
$nuxt.created.call('all')
$nuxt.client.created.call.apply({ n: 1 }, ['client'])
$nuxt.server.created.call('server')
$nuxt.client.aClientHook((type) => console.log('A Client Only Hook: ' + type))
$nuxt.aClientHook.call('all')
$nuxt.client.aClientHook.call('client')
$nuxt.server.aClientHook.call('server')
window.process = { client: false, server: true }
$nuxt.client.anotherClientHook((type) => console.log('Another Client Only Hook: ' + type))
$nuxt.anotherClientHook.call('all')
$nuxt.client.anotherClientHook.call('client')
$nuxt.server.anotherClientHook.call('server')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment