Tommy B.
Tommy B.

Reputation: 3639

Feed an Ember.js template by fetching JSON objects and pushing them in the store

I'm trying to feed a template:

<script type="text/x-handlebars" data-template-name="wineries">
{{#each}}
<p>{{name}}</p>
{{/each}}
</script>

With that route: (look for the comment)

Map.WineriesRoute = Ember.Route.extend({
    model: function() {
        var store = this.get('store');

        return Ember.$.getJSON('/api/wineries').then(function(response) {
            if (response.success) {
                response.data.forEach(function(winery) {
                    store.push('winery', winery);
                });
            }
            // what to do here?
            return store.findAll('winery');
        });
    }
});

And that model:

Map.Winery = DS.Model.extend({
    name:          DS.attr('string'),
    address:       DS.attr('string'),
    address_2:     DS.attr('string'),
    city:          DS.attr('string'),
    stateprovince: DS.attr('string'),
    country:       DS.attr('string'),
    latitude:      DS.attr('float'),
    longitude:     DS.attr('float'),

    full_address: function () {
        return this.get('address') + ' ' + this.get('city') + ' ' + this.get('stateprovince') + ' ' + this.get('country');
    }.observes('address', 'city', 'stateprovince', 'country')
});

I'm getting started with Ember.js and reading LOTS of docs but I'm stuck as I don't know how to handle the store too much even after reading the doc page.

1) What should I do to properly feed the store with the objects? 2) What should I do to properly return the objects after having fed the store? 3) Any other ember-related suggestions?

EDIT:
It seems ember-data isn't what I'm looking for, ember-model seems more fitting for my use-case.

Thanks!

Upvotes: 0

Views: 1483

Answers (2)

sjmog
sjmog

Reputation: 161

TomShreds - if you use the RESTAdapter as Mutual Exception suggests (which I advise too), then you can manually set how models are pluralized:

DS.RESTAdapter.configure("plurals", { winery: "wineries" });

Original answer here: Where do I specify the pluralization of a model in Ember Data?

Upvotes: 1

Mutual Exception
Mutual Exception

Reputation: 1300

First of all: Why do load and push your server data "manually"?

Using DS.RESTAdapter or DS.ActiveModelAdapter you can let ember-data load your items automagically from a REST API. See here for more details.

Your could then simplify your route class like this:

Map.WineriesRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('winery');
    }
});

Upvotes: 2

Related Questions