Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

javascript - JS: examples of class usage in UIs?

I'm learning es6 classes and I'm having a hard time seeing how that would be used in the view. Like if I had a User class, it seems like it'd be more a backend concern:

class User {
   constructor(name, age) {
       this.name = name;
       this.age = age;
   }

   giveIntro() {
       return 'Hi, I am ' + this.name + ' and I am ' + this.age + ' years old'
   }
}
  1. Why would user creation happen on the frontend rather than giving the data to a backend to store & save where it could persist?
  2. How could this 'feed' the UI the data it needs to make a list of users?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the class as a model on the front-end. It will be used to store data that can then be used later when rendering.

class User {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  giveIntro() {
    return `Hi, my name is ${this.name} and I am ${this.age} years old.`
  }
}

const users = [];

const addUser = (e) => {
  const form = e.target;
  const name = form.elements.name.value;
  const age  = form.elements.age.value;
  const user = new User(name, isFinite(age) ? age : undefined);
  users.push(user);
  form.reset();
  renderUsers();
};

const renderUsers = () => {
  const results = document.querySelector('.results');
  const oldList = results.querySelector('ul');
  if (oldList) {
    results.removeChild(oldList);
  }
  const list = document.createElement('ul');
  users.forEach(user => {
    const item = document.createElement('li');
    item.textContent = user.giveIntro();
    list.append(item);
  });
  results.append(list);
};

const userForm = document.forms['person'];

userForm.elements.name.value = 'John Doe';
userForm.elements.age.value = 42;

userForm.addEventListener('submit', addUser);
form div > label {
  display: inline-block;
  width: 4em;
  font-weight: bold;
}
<form name="person" onsubmit="return false;">
  <div>
    <label>Name</label>
    <input type="text" name="name" />
  </div>
  <div>
    <label>Age</label>
    <input type="number" name="age" min="1" />
  </div>
  <button type="submit">Submit</button>
</form>
<hr />
<h2>Results</h2>
<div class="results"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...