Costa
Costa

Reputation: 654

Emberjs array controller

My route is:

export default Ember.Route.extend({
    model: function (params) {
        var blocks = this.store.find('block', {'objectId': 777});
        this.controllerFor("blocks").set('model', blocks);
        return Ember.RSVP.hash({
            object: this.store.find('object', params.id),
            blocks: blocks
        });
        //return this.store.find('object', params.id);
    }
});

My controller is:

export default Ember.ArrayController.extend({
    init: function(e){
        alert('jere');
    }
});

Alert in init function works but next I get the error:

Error while processing route: objects.bc.index Cannot read property 'length' of null TypeError: Cannot read property 'length' of null

What is the right way to get collection of models through ajax and show it in template with custom array controller?

Upvotes: 2

Views: 172

Answers (1)

user663031
user663031

Reputation:

This code has a number of problems. First, ArrayController assumes that its model is an array, whereas your model hook is returning a hash. Second, your this.controllerFor("blocks").set('model', blocks) call attempts to set the model for the controller to a promise, which is useless. You do not set the model for the controller in the model hook like this. You set it by returning the model, which is then installed (after it resolves) into the controller by your (or the default) setupController hook.

You should not use an ArrayController, which is soon to be deprecated anyway, and instead use a plain old controller. The model for this controller will be the hash returned from the model hook. You need to access it explicitly in the template with {{model}}.

So you want something like this:

// route.js
export default Ember.Route.extend({
    model: function(params) {
        var blocks = this.store.find('block', {'objectId': 777});
        return Ember.RSVP.hash({
            object: this.store.find('object', params.id),
            blocks: blocks
        });
    }
});

// controller.js
export default Ember.Controller.extend({
    init: function(e) {
        alert('jere');
    }
});

In your templates, instead of

{{#each controller}}
    blockProp is {{blockProp}}

as you are presumably doing now, use

{{#each block in model.blocks}}
    blockProp is {{block.blockProp}}
{{/each}}
And objectProp is {{model.object.objectProp}}

Upvotes: 1

Related Questions