How would I write something like select view as a component?


#1

Ember has a select view which is a view that generates subviews for it’s option tags. Would it be possible to make a component that can generate sub tags within itself? Similar to:

Spark.InputFieldComponent = Ember.Component.extend({
   tagName: "select",
   setup : function() {
   var testView = Ember.View.extend({
      tagName : "div"
   });
   this.set("childViews", [testView]);
}.on("init")

That could generate something like:

<select>
  <option></option>
</select>

#2

Here is a quick example that I created:

It is a basic example that can be extended to support multi-select and more complex use cases.


#3

I expanded on what you built to allow for selected to be bound http://emberjs.jsbin.com/wiwuguhe/5/edit


#4

What I’m trying to do is get all the possible input tags (including textarea and select) and make them into a single component that is passed a configuration and builds itself.

I think this would mean that I’d have to make the option tags within the component itself and not in the template.

I think a container view can add child views but is there any way a component could as well?


#5

What is the reason to create a massive “god” component? To me a textarea and a select input are so different that you wouldn’t gain anything by trying to couple them.


#6

It is not the place of mortals to question god. In all seriousness though it was mostly to avoid creating a giant if statement in my input generation and because I saw that Ember.Select was able to add sub elements to itself, so I wanted to know how to do the same.


#7

Basically something that implements the factory pattern to spit out inputs. Let be brain storm this one…


#8

It is a bad idea to try to build up your component by directly modifying childViews. That’s only officially supported for ContainerView. And it’s not necessary to achieve the factory pattern you’re talking about. You can still do all of that directly from your component’s template:

{{#if iAmTextArea}}
  {{textarea value=value cols=cols rows=rows}}
{{/if}}

{{#if iAmSelect}}
  {{view Ember.Select content=content value=value}}
{{/if}}

{{#if iAmInput}}
  {{input type=type value=value}}
{{/if}}

Then implement iAmSelect and friends as computed properties on your component, based on the configuration you pass in.