简体   繁体   中英

In Ember how can I have different html in a component used in multiple places?

I'm trying to make a dropdown component that can have different HTML in the heading/title. I have this so far:

component:

export default Ember.Component.extend({
  tagName: 'span',
  isOpen: false,
  classNames: ['dropdown-toggle'],

  mouseEnter: function() {
    if (!this.get('isOpen')) {
      this.set('isOpen', true);
    }
  },

  mouseLeave: function() {
    if (this.get('isOpen')) {
      this.set('isOpen', false);
    }
  },

  click: function() {
    if (this.get('isOpen')) {
      this.set('isOpen', false);
    }
  }
});

component template:

{{title}}<i class="fa fa-chevron-down"></i>
{{#if isOpen}}
  {{yield}}
{{/if}}

application template:

  {{#dropdown-menu title=fullName}}
  <ul role="menu">
    <li><a href="#">Item 1</a></li>
    <li class="divider hidden-xs"></li>
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a></li>
  </ul>
  {{/dropdown-menu}}

So the dropdown initially starts closed, displaying only the title (which is passed in) and some markup, displaying a thing to hover over and the content is revealed by some actions.

I'd like to be able to specify that heading/title markup each time I use the component but I can't figure out how.

For example maybe I want another dropdown somewhere on the page but I'd like to include an image in the header or some other markup.

Is this possible or would I have to make separate components for each type of dropdown? Like {{generic-dropdown}} and {{image-dropdown}}

If you want to get your project done quickly, then yes, just implement {{button-dropdown}} and {{image-dropdown}} .

Or, you could consider an approach where you implement the desired headers as components themselves:

button-header/template.hbs

<button {{action 'toggle'}}>{{content}}</button>

image-header/template.hbs

<img src="{{content}}">

Now you can define the component as

test-show/template.hbs

{{#component header content=content}}
    {{yield}}
{{/component}}

This uses the new component helper.

You would call this as

my-template.hbs

{{#test-show header='image-header' content='kitten.png'}}
    This is some content.
{{/test-show}}

Untested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM