Mobx-riot observe example

by Maksim Kachurin

HTML

<script src="https://unpkg.com/[email protected]/lib/mobx.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/riot+compiler.min.js"></script>
<my-tag></my-tag>

JavaScript

window.person = mobx.observable({
  firstName: 'Matt',
  lastName: 'Ruby',
  age: 20,
  skills: [
    'javascript'
  ],

  // mobx cached getter
  get fullName() {
    console.log('fullName getter fired');
    return this.firstName + ' ' + this.lastName;
  }
});


// RIOT TAG AS ES6 CLASS
//mobx.autorun(() => { // you can wrap all tag ...
class MyTag extends riot.Tag {
  get name() {
    return 'my-tag';
  }

  get tmpl() {
    return (
      `<div>
         <h3>{ person.fullName }</h3>
         <p>Age: { person.age }</p>
         <p>Skills:</p>
         <ul>
             <li each="{ s, i in person.skills }">{ i + 1 }. { s }</li>
         </ul>
       </div>`
    );
  }

  onCreate(opts) {
    mobx.autorun(() => { // ... or only onCreate with this.update() call
      this.update({
        person: opts.person
      });
    });
  }
}
//});

const tag = new MyTag(document.querySelector('my-tag'), {
  person
}).mount();

// add PHP skill to Matt Ruby
setTimeout(() => {
  person.skills.push('PHP');
}, 2000);

// change all fields
setTimeout(() => {
  mobx.runInAction(() => {
    person.firstName = 'Lissy';
    person.lastName = 'Robin';
    person.age = 35;
    person.skills = [
      'Ruby',
      'JavaScript',
      'TypeScript'
    ];
  });
}, 6000);