Is it possible to use one generic template for several different underlying models in Handlebars.js with Ember.js?

StackOverflow https://stackoverflow.com/questions/23233612

Question

I defined several (10+) different models in Ember and set up the resource routes. Everythings works fine. Although every model has different attributes I want to save me time writing redundant code. Let's start with the models first. Here are some examples...

Model: Client

App.Client = DS.Model.extend({               
    name: DS.attr('string'),
    clientId: DS.attr('string'),
    clientSecret: DS.attr('string'),
    trustedClient: DS.attr('boolean')
});

Model: Group

App.Group = DS.Model.extend({               
    name: DS.attr('string'),
    groupType: DS.attr('string')
});

Model: User

App.User = DS.Model.extend({               
    email: DS.attr('string'),
    password: DS.attr('string'),
});

and more...

Question:

Is it possible to use one (instead of 10+) handlebars template to generate labels and textfields for every attribute and value combination?

Idea

I got some ideas from this question here on stackoverflow. It already seems quite useful to define a general template as proposed.

<script type="text/x-handlebars" data-template-name="general-table-output">
    {{#each metadata}}
        <label>{{name}}</label>
        {{input valueBinding='name'}}        
    {{/each}}
</script>

And then we can use the render helper to pass a model to the controller of general-table-output. Here an example for User.

<script type="text/x-handlebars" data-template-name="user">
    {{render 'general-table-output' user}}
</script>

Up until here everything seems fine... But the controller does not seem to find the model's attributes.

Controller

App.GeneralTableOutput = Ember.ObjectController.extend({
    metadata: function() {
        var vals = [];
        var attributeMap = this.get('content.constructor.attributes');
        attributeMap.forEach(function(name, value) {
            vals.push(value);   
        });
        return vals;
    }.property('content')
});

Problem

attributeMap: undefined

Do you know a way to access an assigned model in the controller and map out all the attributes / values, so that it can be viewed in a generic template?

Was it helpful?

Solution

getting the attributes is a little tricky when working with Ember Data. This is due to Ember Data overriding the default implementation of Ember.get so when you call get on an Ember Data object it skips its internal properties etc going for the model properties (dirty or committed). You'd need to do Ember.get(this.get('content'), 'constructor.attributes').

http://emberjs.jsbin.com/OxIDiVU/394/edit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top