stimulusreflex / stimulus_reflex

Build reactive applications with the Rails tooling you already know and love.

Home Page:https://docs.stimulusreflex.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Refactor `schema.js`

marcoroth opened this issue · comments

Feature Request

This is more like a refactoring idea for the schema.js file at:

export default {
set (application) {
schema = { ...defaultSchema, ...application.schema }
for (const attribute in schema) {
Object.defineProperty(this, attribute.slice(0, -9), {
get: () => {
return schema[attribute]
}
})
}
}
}

The current approach uses Object.defineProperty to define properties on the exported object so that you can call something like Schema.reflex to access the value of schema['reflexAttribute'].

Is your feature request related to a problem?

Kinda, in #606 I added some tests which led to, that Schema.set(application) was called multiple times, which resulted in this error:

  TypeError: Cannot redefine property: reflex
      at Function.defineProperty (<anonymous>)
      at Object.set (javascript/schema.js:25:16)
      at initialize (javascript/stimulus_reflex.js:57:10)
      at o.<anonymous> (javascript/test/reflexes.setupDeclarativeReflexesForElement.test.js:13:5)

To workaround the issue I wrapped the Object.defineProperty() call in an if (!this.hasOwnProperty(attributeName) so that it doesn't try to redefine the property if it's already defined.

Describe the solution you'd like

I think a Proxy might be a better solution here, since that doesn't require to rewrite any properties. This would also allow Schema.set(application) to be called multiple times without throwing an error.