Reputation: 2191
I am trying to create a list of users (that are friends with the logged in user), but I don't know how to inject the user into my view.
I have tried with several injections:
Ember.Application.initializer({
name: "currentUser",
initialize: function(container, application) {
var store = container.lookup('store:main');
container.register('user:current', store.find('user', 1), { instantiate: false, singleton: true });
}
});
and...
Ember.Application.initializer({
name: "injectCurrentUser",
after: 'currentUser',
initialize: function(container) {
// .... here are some other injections missing
container.injection('view:default', 'currentUser', 'user:current');
container.typeInjection('view', 'currentUser', 'user:current');
container.injection('view:friendselect', 'currentUser', 'user:current');
}
});
No matter how I try to inject my user into my view, its not available in my contentbinding. My view now has this ugly workaround:
GambifyApp.FriendSelectView = Ember.CollectionView.extend({
init: function(){
this.set('currentUser',this.container.lookup('user:current'))
this.set('content', this.get('currentUser.friends'));
return this._super()
},
// templateName: 'user',
contentBinding: 'currentUser.friends',
// userBinding: 'App.User',
tagName: 'ul',
emptyView: Ember.View.extend({
template: Ember.Handlebars.compile("You have no friends")
}),
itemViewClass: Ember.View.extend({
// userBinding: 'parentView.users',
templateName: 'friend_select'
})
});
I have explained my whole use case in this question: https://stackoverflow.com/questions/21999494/view-design-for-a-list-of-checkboxes-in-order-to-select-users. Maybe injecting the current user is the wrong approach, but I don't know any better one.
Upvotes: 1
Views: 129
Reputation: 51717
I'm doing something similar in my application, but instead of making an API request for the current user, I'm embedding them in the page's HTML when it loads and serializing the data from there. Some parts of this might still be relevant to you though. Since your view has access to the controller, you should be able to inject the user into the controller instead of the view. In your second example, I would try something like this:
I have a CurrentUser controller:
App.CurrentUserController = Ember.ObjectController.extend({});
And then in my application initializer, I create an instance of the user, set the content of my CurrentUserController to that instance, and then inject that controller into all the controllers in my app:
user = store.find('user', 1);
// Put the user instance into the content variable of CurrentUserController
controller = container.lookup('controller:currentUser').set('content', user);
// Perform typeInjection on all the controllers in our app to give them
// currentUser variable so that we don't need to set it manually.
container.typeInjection('controller', 'currentUser', 'controller:currentUser');
Upvotes: 1