【问题标题】:How to encapsulate state with an update method and a mithril component如何用更新方法和秘银组件封装状态
【发布时间】:2019-10-06 19:02:23
【问题描述】:

我想渲染每个请求动画帧都会更新的状态。

我想用更新方法和相应的组件封装状态:

但这失败了,因为它不是正确使用秘银组件。

import * as Vnode from 'mithril/render/vnode';
import * as h from 'mithril/hyperscript';

export default function Play() {
    // background is another encapsulation like Play
  let background = new Background(this);

  let data;

  this.init = d => {
    data = d;
    background.init();
  };

  this.update = delta => {
    background.update(delta);
  };

  this.component = ({
    view() {
    return h('div.' + data,
             [Vnode(background.component)]
              );
    });

}

渲染代码:

import mrender from 'mithril/render';
import * as Vnode from 'mithril/render/vnode';


export default function MRender(mountPoint) {

  this.render = (component) => {
    mrender(mountPoint, Vnode(component));
  };

}

用法:

let mrender = new MRender(element);

let play = new Play();

function step() {
  play.update();
  mrender.render(Vnode(play.component));
  requestAnimationFrame(step);
};

step();

我希望状态突变和渲染代码在同一个地方,因为状态与视图动画有关。

【问题讨论】:

    标签: javascript mithril.js


    【解决方案1】:

    如果我理解正确,您希望能够在 requestAnimationFrame 更新组件时管理组件的内部状态?以下内容可能会让您走上正轨:

    const m = require('mithril');
    
    //Use a closure to manage internal state of component
    const play = initialVnode => {
    
      const { 
        timestamp
      } = initialVnode.attrs;
    
      const start = timestamp;
    
      return {
    
        view: vnode => m('ul',[
            m('li',`Start: ${start}`),
            m('li',`Current timestamp: ${vnode.attrs.timestamp}`),      
        ])
      }
    };
    
    let reqID;
    
    const step = timestamp => {
    
      if( timestamp ){ //Start animating when timestamp is defined 
    
          m.render(document.body, m(play,{
            timestamp,
          }));
      }
    
      reqID = requestAnimationFrame(step);
    
      if( reqID === 60 ){ //Add condition to stop animating
         cancelAnimationFrame(reqID);
      }
    
    };
    
    step();
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 2017-01-20
      • 2023-02-11
      • 2021-11-15
      • 1970-01-01
      相关资源
      最近更新 更多