|
@@ -1,19 +1,15 @@
|
|
|
-import { domReady, buildInitExpression, isNullOrUndefined } from './utils'
|
|
|
+import { domReady } from './utils'
|
|
|
import { createObservable } from './observable'
|
|
|
import EventBus from './bus'
|
|
|
|
|
|
const Spruce = {
|
|
|
- options: {
|
|
|
- globalStoreVariable: false,
|
|
|
- },
|
|
|
-
|
|
|
events: EventBus,
|
|
|
|
|
|
stores: {},
|
|
|
|
|
|
subscribers: [],
|
|
|
|
|
|
- start: async function () {
|
|
|
+ async start() {
|
|
|
await domReady()
|
|
|
|
|
|
this.emit('init')
|
|
@@ -23,32 +19,29 @@ const Spruce = {
|
|
|
document.addEventListener('turbolinks:render', this.attach)
|
|
|
|
|
|
this.stores = createObservable(this.stores, {
|
|
|
- set: (target, key, value, oldValue) => {
|
|
|
- this.events.runWatchers(this.stores, target, key, oldValue)
|
|
|
+ set: (target, key, value) => {
|
|
|
+ this.events.runWatchers(this.stores, target, key, value)
|
|
|
|
|
|
this.updateSubscribers()
|
|
|
}
|
|
|
})
|
|
|
-
|
|
|
- if (this.options.globalStoreVariable) {
|
|
|
- document.querySelectorAll('[x-data]').forEach(el => {
|
|
|
- if (! this.subscribers.includes(el)) {
|
|
|
- this.subscribers.push(el)
|
|
|
- }
|
|
|
- })
|
|
|
-
|
|
|
- window.$store = this.stores
|
|
|
- }
|
|
|
},
|
|
|
|
|
|
attach() {
|
|
|
- document.querySelectorAll('[x-subscribe]').forEach(el => {
|
|
|
- el.setAttribute('x-init', buildInitExpression(el))
|
|
|
- el.removeAttribute('x-subscribe')
|
|
|
+ if (! window.Alpine) {
|
|
|
+ throw new Error('[Spruce] You must be using Alpine >= 2.5.0 to use Spruce.')
|
|
|
+ }
|
|
|
+
|
|
|
+ const self = this
|
|
|
+
|
|
|
+ window.Alpine.addMagicProperty('store', el => {
|
|
|
+ self.subscribe(el)
|
|
|
+
|
|
|
+ return self.stores
|
|
|
})
|
|
|
},
|
|
|
|
|
|
- store: function (name, state) {
|
|
|
+ store(name, state) {
|
|
|
if (! this.stores[name]) {
|
|
|
this.stores[name] = state
|
|
|
}
|
|
@@ -56,28 +49,24 @@ const Spruce = {
|
|
|
return this.stores[name]
|
|
|
},
|
|
|
|
|
|
- reset: function (name, state) {
|
|
|
+ reset(name, state) {
|
|
|
this.stores[name] = state
|
|
|
},
|
|
|
|
|
|
subscribe(el) {
|
|
|
- this.subscribers.push(el)
|
|
|
+ if (! this.subscribers.includes(el)) {
|
|
|
+ this.subscribers.push(el)
|
|
|
+ }
|
|
|
|
|
|
return this.stores
|
|
|
},
|
|
|
|
|
|
updateSubscribers() {
|
|
|
- this.subscribers.forEach(el => {
|
|
|
- if (el.__x !== undefined) {
|
|
|
- el.__x.updateElements(el)
|
|
|
- }
|
|
|
+ this.subscribers.filter(el => !! el.__x).forEach(el => {
|
|
|
+ el.__x.updateElements(el)
|
|
|
})
|
|
|
},
|
|
|
|
|
|
- config(options = {}) {
|
|
|
- this.options = Object.assign(this.options, options)
|
|
|
- },
|
|
|
-
|
|
|
on(name, callback) {
|
|
|
return this.events.on(name, callback)
|
|
|
},
|