mathigon / textbooks

Source code of Mathigon's interactive textbooks
https://mathigon.org
357 stars 154 forks source link

I do not understand `$step.model.*` #118

Closed ouronghuang closed 4 years ago

ouronghuang commented 4 years ago

Codes:

  $step.model.rad = (r: number) => {
    const a = r / Math.PI;
    return a > 1.99 ? 2 : round(a, 2);
  };

  const zero = new Point(240, 140);
  const center = new Point(140, 140);
  const ends = [new Point(240, 140.4), new Point(40, 140), new Point(140, 40)];

  function setState(i: number) {
    const arc1 = new Angle($step.model.a, center, zero).arc;
    const arc2 = new Angle($step.model.b, center, ends[i]).arc;

    animate((p) => {
      $step.model.a = arc1.at(p);
      $step.model.b = arc2.at(p);
    }, 600);
  }

How do I understand $step.model.rad, $step.model.a and $step.model.b ?

When I try write that:

import { SVGParentView, observe } from '@mathigon/boost';

const $svg = new SVGParentView(document.getElementById('svg'));

console.log($svg.model);

$svg.bindModel(observe($svg.$('.a')));
$svg.bindModel(observe($svg.$('.b')));

console.log($svg.model);
// => Only one

So what can I bind model for myself?

plegner commented 4 years ago

Thanks for the question! You should never use the SVGParentView constructor directly – instead, you can do something like const $svg = $N('svg') which is a shortcut for document.createElement().

The observer() function takes an object as argument, which contains the initial state of the model, and .bindModel() should only be called a single time for every DOM element.

For example, something like this:

<svg id="canvas"><circle :cx="point.x" :cy="point.y" r="20"/></svg>
const $svg = $('#canvas');  // Select the <svg>
const model = observer({point: new Point(10, 10)});
$svg.bindModel(model);

model.point = new Point(20, 20);  // position of the <circle> will automatically change

You can have a look at https://github.com/mathigon/boost.js/blob/master/src/elements.ts for the source code, and we are working on some additional documentation.

ouronghuang commented 4 years ago

Thank you so much!