Skip to content

How to get the component contents within Javascript when the sub-components are dynamically created? #3409

Description

@ceremcem

Description:

I've my reasons to re-invent the radio buttons with <button> elements (like displaying "loading" icon and confirming database writes before displaying a "selected" tick). This is the stripped down version of my radio-buttons component (playground):

Ractive.components['radio-buttons'] = Ractive.extend({
  template: `{{>content}}`,
  oninit: function(){
    setSelection = (selection) => {
      // do something else, like setting button colors
      this.fire('select', selection)
    }
    this.on({
      '*.init': (ctx, instance) => {
        instance.on('click', (ctx2) => {
          setSelection(instance.partials.content[0])
        })
      }
    })
	}
})

Ractive.components['radio-button'] = Ractive.extend({
  template: `<button on-click="click">{{yield}}</button>`
})

new Ractive({
  target: 'body',
  template: `
  <radio-buttons on-select="radioSelected">
  	<radio-button>hello</radio-button>
  	<radio-button>there</radio-button>
  </radio-buttons>  
  `,
  on: {
    radioSelected: function(ctx, selection){
      alert("selection is: " + selection)
    }
  }
})

However, when I try to create the radio-buttons with an {{#each}} loop, buttons' on-click handler doesn't work as intended: playground:

  <radio-buttons on-select="radioSelected">
    {{#each myArray}}
      <radio-button>{{.}}</radio-button>
    {{/each}}
  </radio-buttons>  

Expected output when we click on [a] button: selection is: a
Observed output is: selection is: undefined

How can I make it work when I create the sub-components dynamically? What becomes different when we encapsulate the sub-components into the {{#each}} loop?

Versions affected:

1.4

Platforms affected:

Browser

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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