NicholasJohn16
NicholasJohn16

Reputation: 2409

Loading models in Component

I've made a component that produces a drop down list used to select an item from a possible list of items based on the passed in type:

{{item-selector type="type1"}}

I dont want to load the items on page load cause theres potentially a lot of them and many times they won't need to be loaded. I would prefer loading them on user interaction with the component. That nixes out loading them in the route.

Since components don't have access to the store, I've been experimenting with passing in a controller for the items:

{{item-selector type="type1" widget=controllers.type1}}

I'm using widget cause I can't think of a better property name and controller is already taken. Suggestions welcome.

But now I'm unsure about how to load the models in the controller. Should I do it in init? Or maybe a computed property? I'm unsure.

Suggestions on how to solve this would be appreciated.

Upvotes: 0

Views: 524

Answers (1)

Asgaroth
Asgaroth

Reputation: 4334

Thanks to two way databinding you can just pass an empty array, that will populate only when needed.

{{item-selector type="type1" items=items action="loadItems"}}

Here we are passing items as the elements of your list, which at the beginning would be empty. we are also passing an action, that would ask the route to load the items on demand.

// controller.js

export default Ember.ArrayController.extend({
  items: null
});

// route.js

export default Ember.Route.extend({
  actions: {
    loadItems: function() {
      var controller = this.get('controller');

      this.store.find('item').then(items => {
        controller.set('items', items);
      });
    }
  }
});

Some where in your component, you will be firing the action to load the items as part of the user interaction you mentioned.

Upvotes: 6

Related Questions