Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to pass arguments to component constructor #668

Closed
YerkoPalma opened this issue Jun 20, 2018 · 2 comments
Closed

How to pass arguments to component constructor #668

YerkoPalma opened this issue Jun 20, 2018 · 2 comments

Comments

@YerkoPalma
Copy link
Member

This is more a question than an issue. I looked quickly at the source and though that I could pass arguments to components constructor trhough the cache method of the state. I tried this:

// component
var Component = require('choo/component')
var html = require('choo/html')

class Button extends Component {
  constructor (text) {
    super()
    console.log(arguments)
    this.text = text || ''
  }

  createElement () {
    return html`
      <button>${this.text}</button>
    `
  }

  update () {
    return false
  }
}

module.exports = Button
// view
function view (state, emit) {
  if (state.title !== TITLE) emit(state.events.DOMTITLECHANGE, TITLE)

  return html`
    <body class="code lh-copy">
      <main class="pa3 cf center w3">
          <h2>I</h2>
          ${state.cache(Button, 'button', 'Hello world').render()}
      </main>
    </body>
  `
}

But that outputted <button>hello</button>. And the console log with arguments in the constructor gives me

Arguments(4)
0: "button"
1: {events: {…}, components: {…}, title: "welcome - main", cache: ƒ, href: "", …}
2: ƒ ()
3: "Hello world"
callee: (...)
length: 4
Symbol(Symbol.iterator): ƒ values()
get callee: ƒ ()
set callee: ƒ ()
__proto__: Object

Is that the intended behaviour? If that's the case, then is safe to assume that all components rendered through cache get the same signature

constructor (id, state, emit, ...args) {}
@tornqvist
Copy link
Member

That's right, state and emit are prefixed to the constructor arguments and the cache arguments are:

state.cache(Component, 'unique-id', ...args)

I'd be happy to contribute to the choo/component docs to help get this out there.

@YerkoPalma
Copy link
Member Author

Closing this questions because it is answered. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants