Skip to content

createElement called multiple times even when update always return false #88

@mafintosh

Description

@mafintosh

There is a decent chance I misunderstood the README, but I was expecting createElement only be called once if update always returned false, to make embedding of other DOM elements easier.

This doesn't always seem to be the case when using multiple components. Here is a test-case:

// save as app.js

var html = require('nanohtml')
var morph = require('nanomorph')
var Button = require('./component.js')

var c1 = new Component('a')
var c2 = new Component('b')

var tick = 0

// render both 10 times
for (var i = 0; i < 10; i++) {
  render(c1)
  render(c2)
}

// some render function that just updates a counter
function render (c) {
  const b = html`<body>
      ${c.render('hi:' + tick++)}
    </body>`

  morph(document.body, b)
}
// save as component.js

// This component is the one from the README in the section about mutable components.
// Modified to write out every time createElement is called.

var Nanocomponent = require('nanocomponent')
var html = require('nanohtml')
 
class Component extends Nanocomponent {
  constructor () {
    super()
    this.text = ''
  }
 
  createElement (text) {
    console.log('Calling createElement')
    this.text = text
    return html`<h1>${text}</h1>`
  }
 
  update (text) {
    if (text !== this.text) {
      this.text = text
      this.element.innerText = this.text   // Directly update the element
    }
    return false                           // Don't call createElement again
  }
 
  unload (text) {
    console.log('No longer mounted on the DOM!')
  }
}

module.exports = Component

Running the above app will result in 20 createElements being written out. If only one component is used then it's only written out once. Is that working as expected? If so how would you embed a third party dom element.

For now we've published a fork of nanomorph that supports short circuiting "guarded" elements for this using https://github.com/hyperdivision/nanomorph/blob/master/index.js#L63 and https://github.com/hyperdivision/nanomorph-guard

Thanks for all the great stuff btw! :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions