silvenon
silvenon

Reputation: 2197

How to map component's properties to the model?

In my Ember app I'm iterating through an array of models and rendering a component for each one:

{{#each}}
  {{content-box provider=provider type=type author=author link=link createdDate=created_date media=media summary=summary text=text title=title thumbnails=thumbnails}}
{{else}}
  No results :(
{{/each}}

As you can see, there is a lot of redundancy in this mapping. Is there a way to just map all properties at once?

Should I be using a view? I'm still pretty confused when to use a view vs. component. I've read a couple of articles about that and I got the impression that I should be using a component when I want reusability, which seems right here.

Upvotes: 1

Views: 91

Answers (2)

Duncan Walker
Duncan Walker

Reputation: 2201

It is possible to easily pass all those parameters as a single object inside the {{#each}} helper. In your view template:

{{#each}}
  {{content-box content=this}}
{{/each}}

And, in your component template:

{{#with content}}
  Provider: {{provider}}
  Type: {{type}}
{{/with}}

Here is a working JSBin.

FYI, You can name the content property anything you like. The {{with}} helper is optional but means you shorten {{content.provider}} to {{provider}}.

Upvotes: 1

givanse
givanse

Reputation: 14943

It is not possible to pass all those parameters with a single attribute. Having so many parameters is actually a bad smell, refactor and take out of the component all that is not indispensable for its function.

Say you have:

<script type="text/x-handlebars" data-template-name="components/my-component">
    label 1 {{attribute1}}
    label 2 {{attribute2}}
    label N {{attributeN}}
    <button {{action "gotClicked" some_id}}>Click Me!</button>
</script>

As it is, you would have to pass several attributes to the component, from 1 to N and some_id, exactly what you are doing.

The thing is that components are designed to be generic pieces of code that can be plugged in into multiple places. Having that in mind, refactor and take out the (accessory) data that its only purpose is to be read/seen by the user.

Something like:

<script type="text/x-handlebars" data-template-name="some-view">
    {{#each}}
        label 1 {{attribute1}}
        label 2 {{attribute2}}
        label N {{attributeN}}
        {{my-component some_id=some_id}}
    {{/each}}
</script>

<script type="text/x-handlebars" data-template-name="components/my-component">
    <button {{action "gotClicked" some_id}}>Click Me!</button>
</script>

Upvotes: 1

Related Questions