Pergunta

I'm new to ember, so maybe I'm doing this wrong.

I'm trying to create a select dropdown, populated with three values supplied from an external datasource. I'd also like to have the correct value in the list selected based on the value stored in a different model.

Most of the examples I've seen deal with a staticly defined dropdown. So far what I have is:

{{#view contentBinding="App.formValues.propertyType" valueBinding="App.property.content.propertyType" tagName="select"}}
  {{#each content}}
    <option {{bindAttr value="value"}}>{{label}}</option>
  {{/each}}
{{/view}}

And in my module:

App.formValues = {};
App.formValues.propertyType = Ember.ArrayProxy.create({
    content: [
        Ember.Object.create({"label":"App","value":"app", "selected": true}),
        Ember.Object.create({"label":"Website","value":"website", "selected": false}),
        Ember.Object.create({"label":"Mobile","value":"mobile", "selected": false})
    ]
});

And finally my object:

App.Property = Ember.Object.extend({
    propertyType: "app"
});

App.property = Ember.Object.create({
    content: App.Property.create(),

    load: function(id) {
      ...here be AJAX  
    }
});

The dropdown will populate, but it's selected state won't reflect value of the App.property. I know I'm missing some pieces, and I need someone to just tell me what direction I should go in.

Foi útil?

Solução

The answer was in using .observes() on the formValues. For some reason .property() would toss an error but .observes() wouldn't.

I've posted the full AJAX solution here for reference and will update it with any further developments.

App.formValues = {};
App.formValues.propertyType = Ember.ArrayProxy.create({
    content: [],

    load: function() {
        var that = this;

        $.ajax({
            url: "/api/form/propertytype",
            dataType: "json",
            success: function(data) {
                that.set("content", []);
                _.each(data, function(item) {
                    var optionValue = Ember.Object.create(item);
                    optionValue.set("selected", false);
                    that.pushObject(optionValue);
                });
                that.update();
            }
        });
    },

    update: function() {
        var content = this.get("content");
        content.forEach(function(item) {
            item.set("selected", (item.get("value") == App.property.content.propertyType));
        });
    }.observes("App.property.content.propertyType")
});
App.formValues.propertyType.load();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top