A
A
Artem00712019-01-20 20:59:01
JavaScript
Artem0071, 2019-01-20 20:59:01

Reactive class attributes?

There is a certain component in which I receive data from the api and display them.
The code is something like this:

<template>
  <div v-if="user">
     <input v-model="user.name" />
  </div>
</template>

<script>
export default {
  data: () => ({
    user: null
  }),
  methods: {
    loadUser () {
        this.$api.users.show(userId) {
           //from response get user instance...
          this.user = response
        }
    }
  }
}
</script>

So, I thought about something and wanted to create a separate class with a user model, and at the same time respond to attribute changes. I
came to this structure:
export default class User {
    constructor (payload) {
        this._original = payload
        this._attributes = User.refactorPayload(payload)
        this._changed = {}
    }

And I wanted to display the data in the component as:
user.getAttribute('name')
I did everything, but I ran into a two-way-binding problem
. I have all the attributes contained in _attributes
In general, I don’t know how to make getter-setters in js ...
With getters it turned out through the getAttribute wrapper:
getAttribute(key){
        if (this._attributes.hasOwnProperty(key)) {
            return this._attributes[key]
        }

        return null
}

But if I insert user.getAttribute('name') into the v-model, then nothing will change accordingly.
In general, I don’t know how to organize it correctly ...
Please help.
I don’t want to do it through user._attributes.name, but I want how it's more "correct" or something ..

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Sedyshev, 2019-01-20
@Artem0071

The option "on the forehead" - do not use "sugar" in the form of v-model, but use
In general, why such a strange organization of the model class? Why didn't you explicitly delimit the User properties? There would be both visibility and addition of the code from IDE.
The second option, if you really really want to pervert with a similar implementation of the model, use the getter / setter mechanism of the language itself :

// age будет высчитывать возраст по birthday
  Object.defineProperty(this, "age", {
    get: function() {
      var today = new Date();
      var yearDelta = today.getFullYear() - this.birthday.getFullYear();

      if (today.getMonth() > this.birthday.getMonth() ||
        (today.getMonth() === this.birthday.getMonth() && today.getDate() >= this.birthday.getDate())) {
        return yearDelta;
      }

      return yearDelta - 1;
    }
  });

G
grinat, 2019-01-20
@grinat

The hell are you doing this shit? Vue already declares reactive getters and setters for you: https://github.com/vuejs/vue/blob/dev/src/core/obs... there are two way binding and everything else is already there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question