Data Maps for inherited controller


#1

I would like to know what do you think about the possibility to write code like the following:

import { Controller } from "stimulus"

export default class ParentController extends Controller {
  whoAmI() {
    console.log("${this.data.get('name')}, I'm your father!")
  }
}

export default class ChildController extends ParentController {
  connect() {
    this.whoAmI()
  }
}

<div data-controller="child" data-parent-name="Lucky"></div>

Is it something interesting to support in the framework? Do you have any suggestion to bind data to the parent controller?

Thanks!


#2

Unless I miss something, this does already work. It is mostly ES6 class inheritance.

However, there is a typo in your example

it should be

<div data-controller="child" data-child-name="Lucky"></div>

and not

<div data-controller="child" data-parent-name="Lucky"></div>

#3

You get it wrong @adrienpoly, I really want to bind data to the parent controller (be able to see the child as an instance of the parent and bind directly to it).

Why? Think about the template method design pattern, being able to bind to the parent controller let’s you specify data, while the child will implement missing parts of behavior.

I accomplished this, without inheritance, in a search controller. The base search fetches data from the server, caches it and also process queries, and implements some callbacks that must be implemented by a view dependent controller.

I ended with this:

<div data-controller="search-renderer search" data-search-renderer="search-renderer"></div>

Then in my search controller I can get the search renderer with the getControllerForElementAndIdentifier method and call the methods that notify users about the various stages: loading, success, failed and renderResults.

I could use inheritance and change the data-controller for each specific renderer, and maybe the complexity to support the above scenario is not worth it.