Jeff
Jeff

Reputation: 6953

looking up in store from a component

I have a template that includes a component.

// pods/workgroup/template.hbs
...
{{workgroup/member-add
    wgId=model.id
    store=store
    peekUser2Workgroup=peekUser2Workgroup
}}
...

Within that component I need to lookup if something is already present in the store.

//somewhere in components/workgroup/member-add/componsent.js
let alreadyInStore = this.store.peekRecord('user2workgroup',u2wId);

I made it work by injecting the store into the component (as above), which of course is bad practise.
So I tried making a property in my parent-controller that does the store lookup:

//in components/workgroup/member-add/componsent.js
let alreadyInStore = this.get('controller').peekUser2Workgroup(u2wId);


//in pods/workgroup/controller.js
peekUser2Workgroup: function(u2wId) {
    console.log(this);
    console.log(this.store);
    return this.store.peekRecord('user2workgroup',u2wId);
}

This works fine as long as I pass the complete store into the compentent as above.
However, if I don't pass the store to the component it get's undefined, although never accessed from the component directly (the store is present in the controller alone).

Logging into console of this gives me surprisingly the component, not the controller, this.store is undefined.
So I've learned, that with this I don't access the controller itself when a function/parameter gets called from outside/a component.

The question is, how can I make the controller to reference to itself with this?
Or how can I access the store when calling a parameter from outside?
Do I really need to pass the controller itself to himself??
like so:

// in component
let alreadyInStore = this.get('controller').peekUser2Workgroup(this.get('controller'), u2wgId);

//in controller
peekUser2Workgroup: function(myself, u2wId) {
    console.log(this);
    console.log(this.store);
    return myself.store.peekRecord('user2workgroup',u2wId);
}

That seems very odd to me, and looks like I'm shifting around even more than I did initially when simply injecting the store to the controller...

Ember: 2.0.1 Ember-Data: 2.0.0

Upvotes: 0

Views: 151

Answers (1)

NicholasJohn16
NicholasJohn16

Reputation: 2409

Instead of passing the store into the component as a property, inject it using Ember.service like this:

store: Ember.service.inject()

Then instead of passing in the function, just pass in the id vale you're looking up:

{{workgroup/member-add
    wgId=model.id
}}

Now in your component you can fetch the record:

workgroup: function(){
  return this.get('store').peekRecord('user2workgroup', this.get('wgId'));
}.property()

Upvotes: 3

Related Questions