LoginSignup
0
1

More than 3 years have passed since last update.

LitElementでピュアJavaScriptオブジェクトをモデルとして使う例

Last updated at Posted at 2020-08-14
<script type="module">

import { LitElement, html, css } from "https://unpkg.com/lit-element?module"

const createProxy = (target, handler) => new Proxy(target, (function make(handler) {
  return {
    get(target, key) {
      if (typeof target[key] === 'object' && target[key] !== null) {
        return new Proxy(target[key], make(handler));
      } else {
        return target[key];
      }
    },
    set(target, key, value) {
      target[key] = value;      
      handler(target, key, value);
      return true;
    }
  };
})(handler));

class Model {
  constructor() {
    this.count = 0
  }
  increment() {
    this.count += 1
  }
}

class ModelElement extends LitElement {
  constructor() {
    super()
    this.model = createProxy(new Model(), ()=>this.requestUpdate())
  }
}

class ViewElement extends ModelElement {
  static get properties() {
    return {
      //model: { type: Object, noAccessor: true },
      count: { type: Number },
    }
  }
  get count() {
    return this.model.count
  }
  set count(newVal) {
    this.model.count = newVal
  }
  static get styles() {
    return css`
      button {
        font-size: 10em;
      }
    `
  }
  render() {
    return html`
      <button @click="${e=>this.model.increment()}">
        ${this.model.count}
      </button>
    `
  }
}

customElements.define("counter-element", ViewElement)

</script>

<counter-element count="10"></counter-element>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1