marco998
marco998

Reputation: 27

Ember JS : Uncaught TypeError: Cannot read property 'createRecord' of null

I've started to develop an ember JS app using ember cli. For now the idea would be to create svg elements (circles) by keeping the coordinates of a click.

I used a view to capture a mouse click and then pass it to a controller to create the circle with the coordinates. I'm using the fixture adapter to store datas.

The elements I've put manually in the code work fine when I display them. The problem happens when I want to store a new node with my controller, I get the following error :

Uncaught TypeError: Cannot read property 'createRecord' of null

Here is the controller file svg.js :

export default Ember.ObjectController.extend({
    actions:{
        createNode: function(posX,posY){
            var element= this.store.createRecord('element',{ //Here is where I get the error
                text: "element",
                x: posX,
                y: posY,
                graph: 1
            });
            element.save();
        }
    }
});

Here is my template file :

{{#view svg}}
  {{#each item in model}}//For each graph
    {{#each item.elements}}// For each  
        <circle {{bind-attr cx=x}} {{bind-attr cy=y}} r="5" stroke="black" stroke-width="3" fill="yellow" />
    {{/each}}
  {{/each}}
{{/view}}

The associated route :

export default Ember.Route.extend({
    model: function() {
        return this.store.find('graph');
    }
});

The view file :

export default Ember.View.extend({
    tagName: "svg",
    attributeBindings: ['width','height'],
    width: "500",
    height: "500",

    init: function() {
        this._super();
        this.set("controller", svg.create());
    },
    click: function(evt){

        var svg= Ember.$("svg:first");
        var posX = evt.pageX - svg.position().left;
        var posY = evt.pageY - svg.position().top;
        this.get('controller').send('createNode',posX,posY);
    }
});

Maybe I've done something wrong but I don't know why this.store would be null.

Any ideas ?

Thanks in advance!

Upvotes: 1

Views: 2599

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

Whoops, I didn't see what you were doing there in your init. Controllers need to be initialized by the container in order to have dependency injection work with them. Dependency injection injects the store into controllers and routes.

With controllers being deprecated in 2.0 I'd just say move your action from your controller into route/controller that's housing that view. You'd also have to pass the store into the view If you don't want to do that, you can manually define the store on the controller when you're creating it.

Define it on the view

{{#view svg store=store}}

Inject into the view, create an injector and add this

App.inject('view', 'store', 'store:main');

Upvotes: 3

Related Questions