Can I create class inside svelte.js?

Viewed 39

Is it possible to change a variable on input, and that variable is a parameter of a class (OOP code) and automatically changes on input and gets passed to the class?

I am asking because this is the first time I want to use svelte, and I have an entire app of my company written in JavaScript OOP and I want to rewrite it entirely to svelte.

And I wonder if I can copy and paste the old class code and use the bind and other cool stuff from svelte to make it more interesting, and faster and reactive

<script>
let myReactiveVar = "hello";

class myClass {
  constructor(variable) {
    this.variable = variable;
  }

  myMethod() {
    // some code
  }

  get getterVar {
    // return something
  }
}

// here the let variable should always change and passed to the class
// the class is used only for business logic (oop)
let myCreatedClass = new myClass(myReactiveVar)
</script>

// the change happen with input bind.
<input bind:value={myReactiveVar}/>

<p>{myCreatedClass.getterVar}</p>

or should I rewrite the logic with functional programming?

1 Answers

This will not work unless you re-create the class every time you change the variable:

$: myCreatedClass = new myClass(myReactiveVar)

(Which might not be a good idea depending on how expensive it is to create the class and whether you have to retain internal state.)

Other than that you can bind to class variables but internal dependencies will not be tracked, i.e. the property you set has to be the same that you get, e.g.

<script>
    class MyClass {
        constructor(variable) {
            this._variable = variable;
        }
        set variable(value) { this._variable = value; }
        get variable() { return this._variable }
    }
    const myCreatedClass = new MyClass("hello")
</script>

<input bind:value={myCreatedClass.variable} />
<p>{myCreatedClass.variable}</p>

REPL

For everything else there is the option to use stores, which have their own change notifications and thus can be passed around and be handled in external code, but working with them is a bit more complicated than a plain variable.

Related