github / catalyst

Catalyst is a set of patterns and techniques for developing components within a complex application.
https://github.github.io/catalyst/
MIT License
1.36k stars 50 forks source link

Is it possible to use `[target.static]` without TS? #300

Closed omohokcoj closed 1 year ago

omohokcoj commented 1 year ago

I'm following the v2 documentation (https://catalyst.rocks/guide-v2/targets) but the following code snippet doesn't work with JS:

import { actionable, targetable, target } from '@github/catalyst'

export default actionable(targetable(class extends HTMLElement {
  [target.static] = ['fullAddressField'] // on html template there is a data-target="controller-name.fullAddressField" attr

  toggleAddressField () {
    this.fullAddressField.required = false
  }
}))

Is this possible to use this feature in JS or it works only via TS?

keithamus commented 1 year ago

It should be possible. If it doesn't work it may be a bug. I will add a test shortly.

omohokcoj commented 1 year ago

@keithamus turns out with my babel configs which include @babel/plugin-proposal-class-properties the missing static keyword was causing the issue - everything works well with static [target.static] = [] to define targets. Another solution for babel js is to use decorators plugin https://babeljs.io/docs/en/babel-plugin-proposal-decorators

keithamus commented 1 year ago

Thanks for replying back @omohokcoj! Glad you got this solved :raised_hands:

omohokcoj commented 1 year ago

@keithamus btw looks like the issue was not with my babel setup but just in general for JS in browser without any transpiler static [target.static] = ['name'] is the correct way to define the targets (static keyword is missing in the documentation).

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Untitled</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <script type="importmap">
  {
    "imports": {
      "@github/catalyst": "https://ga.jspm.io/npm:@github/catalyst@2.0.0-beta/lib/index.js"
    }
  }
  </script>
  <script async src="https://ga.jspm.io/npm:es-module-shims@1.5.1/dist/es-module-shims.js" crossorigin="anonymous"></script>
  <script type="module">
    import { controller, target } from "@github/catalyst";

    controller(class TestElem extends HTMLElement {
      static [target.static] = ['test'] // static keyword is required

      connectedCallback () {
        console.log(this.test)
      }
    })
  </script>
  <test-elem>
    <div data-target="test-elem.test">
    </div>
  </test-elem>
</body>
</html>

Anyway, thanks for maintaining such a useful library - github/catalyst with native web components looks much better for rails app than hotwire/stimulus 😄

keithamus commented 1 year ago

Thanks! I've fixed the docs in 173a24112109f7c4a9a7bf6b34078522952a2099