hyperapp icon indicating copy to clipboard operation
hyperapp copied to clipboard

Lifecycle Methods - Integration Example

Open cdeutmeyer opened this issue 9 years ago • 1 comments

I feel like the Lifecycle Methods/CodeMirror example is lacking a little. In my opinion, a dev is going to be more interested in tying the the editor's value with the model state than setting it's properties. Also, each lifecycle method is not represented which is why I am still unclear about the use of onRemove.

How do you feel something like the following?

const { h, app } = hyperapp;
/** @jsx h */

// add codepen ref: https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js

const CodeEditor = ({model, actions}) => {

    const setupEditor = (e) => {        
        const editor = ace.edit(e);
        editor.$blockScrolling = Infinity;   
        editor.setTheme("ace/theme/cobalt");
        editor.getSession().setMode("ace/mode/javascript");
        editor.setValue(model.editorText || "", -1);  
        editor.getSession().on('change', (e) => {
            if (editor.curOp && editor.curOp.command.name) { // user change                
                actions.setEditorText(editor.getSession().getValue())
            }
        })
    }
    
    const setEditorText = (e) => {        
        const editor = ace.edit(e);
        const position = editor.getCursorPosition();
        editor.getSession().setMode("ace/mode/javascript");
        editor.setValue(model.editorText || "", -1);  
        editor.moveCursorToPosition(position);      
    }

    const cleanupEditor = (e) => {
        ace.edit(e).destroy()
    }

    return (
      <div style={{ height: "200px", width: "500px" }} onCreate={setupEditor} onUpdate={setEditorText} onRemove={cleanupEditor}></div>                      
    )

}

app({  
  model: { editorText: "console.log(\"Hello World!\");" },
  actions: { 
    setEditorText: (model, text) =>  ({editorText : text })
  },
  view: (model, actions) => (
      <div>
          <input value={model.editorText} style={{ marginBottom: "5px"}} type="text" oninput={ (e) => actions.setEditorText(e.currentTarget.value) } ></input>
          <CodeEditor model={model} actions={actions} ></CodeEditor>
      </div>
   )  
})

cdeutmeyer avatar Mar 15 '17 21:03 cdeutmeyer

@cdeutmeyer Hey, I think I forgot about this one! 🙇

Do you have a live example? CodePen/JSFiddle/Glitch

jorgebucaran avatar Mar 23 '17 03:03 jorgebucaran