Skip to content

Subcomponent Controller access to latest attributes #683

@gilbert

Description

@gilbert

Take the following code:

var ItemManager = {
  controller: function (attrs) {
    this.createItem = function() {
      attrs.items.push( new Item() )
    }
  },
  view: function (ctrl, attrs) {
    return m('.items', [
      m('button', { onclick: ctrl.createItem }, "Create Item"),
      attrs.items.map(...)
    ])
  }
}

I have too often come across the limitation of ItemManager's controller only having access to the first version of attrs. For example:

  1. The parent of ItemManager passes in an array of items:
    a. m.component(ItemManager, { items: itemArray })
  2. Everything works great. Creating an item in ItemManager adds to itemArray.
  3. Later, the parent of ItemManager generates a new value for itemArray, and passes that value to the same ItemManager subcomponent
  4. Things break. Due to the controller's closure to attrs, creating a new item will now add to the old itemArray. The new itemArray remains unaffected.

This is a hard issue to explain, and the workarounds are non-obvious. As it stands, trying to modify the attrs parameter in the controller constructor breaks the principle of least surprise.

I think Mithril should have some built-in way to allow the controller to have access to the latest attrs. I have some options in mind, but before I present them I want to make sure the problem is clear. Thoughts?

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