Mithril.js: How to set focus after redraw?

Created on 17 Mar 2015  路  7Comments  路  Source: MithrilJS/mithril.js

I am implementing an inline editing. After double clicking the text, mithril will redraw it to an input box and I want set focus to the input box.
The problems are

  1. How can I know the redraw process is done then I can call focus on the input?
  2. How can I get the reference of the input box?

Here is a short jsfiddle:
http://jsfiddle.net/newlix/84z7kbk5/

In React I can do with the following code

this.setState({editing:true},function(){
      var node = this.refs.input.getDOMNode();
      node.focus();
}.bind(this));

The second parameter is a callback function that will be executed once setState is completed and the component is re-rendered.

Most helpful comment

@derMart

config was replaced a long time ago by a series of lifecycle methods.

You likely want oncreate

Which would allow you to get a reference to the DOM node once it is created.

m('input', { oncreate: ({dom}) => dom.focus() })

You could also store the reference to the dom node instead of calling it on the spot and use it later for focusing it under different conditions if necessary.

All 7 comments

Did you check the TodoMVC with Mithril?
This is how they did it:
https://github.com/tastejs/todomvc/blob/gh-pages/examples/mithril/js/views/main-view.js#L64
You need to use config http://lhorie.github.io/mithril/mithril.redraw.html#changing-redraw-strategy

Thank you!

though this is very old, I am having the same issue.
Is this config function deprecated? Or does it just work inside TodoMVC?
Does not seem to do be called in vanilla mithril v2 where I need a solution for...

@derMart

config was replaced a long time ago by a series of lifecycle methods.

You likely want oncreate

Which would allow you to get a reference to the DOM node once it is created.

m('input', { oncreate: ({dom}) => dom.focus() })

You could also store the reference to the dom node instead of calling it on the spot and use it later for focusing it under different conditions if necessary.

@derMart as @fuzetsu said, you need to use the lifecycles. If you want to get the input after double-click, then you can use onupdate: ({dom}) => dom.focus(), as I you can see here in my version of the TodoMVC.

thnx alot, yes, both are elegant solutions.

And for future reference, please file new issues with these kinds of questions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

designMoreWeb picture designMoreWeb  路  4Comments

marciomunhoz picture marciomunhoz  路  4Comments

omenking picture omenking  路  3Comments

volnei picture volnei  路  3Comments

tivac picture tivac  路  3Comments