how to get the store in a component in ember.js

老子叫甜甜 提交于 2019-12-19 17:39:32

问题


How in the world do i get a handle on the store inside of a component? I'm trying to create an auto-complete component that returns results from the store.

App.AutoCompleteComponent = Ember.Component.extend({

    //-------------------------------------------
    // Ember Properites
    //-------------------------------------------
    content: Ember.ArrayController.create(),

    //-------------------------------------------
    // Instance Properties
    //-------------------------------------------
    queryText: "",

    componentItemSelected: null,

    //-------------------------------------------
    // Observers
    //-------------------------------------------
    queryTextChanged: function () {
        this.updateContent(this.get("queryText"));
    }.observes("queryText"),

    //-------------------------------------------
    // Instance Methods
    //-------------------------------------------
    selectItem: function (item) {
        this.set("componentItemSelected", item);
    },

    updateContent: function (queryText) {

        if (queryText.length <= 5) {

            console.log('not greater than 5 chars');
            return;
        }

        this.get("content").setObjects([]);

        var items = App.Company.find();

        this.get("content").setObjects(items);
    }
});

here is my company model

App.Company = DS.Model.extend({

  name: DS.attr('string'),

  created_at: DS.attr('date'),

  updated_at: DS.attr('date'),

  people: DS.hasMany('person')

});

I've tried:

  • this.get('store')
  • DS.Store.find('company')
  • just store
  • App.Company.find()

I always get an Uncaught TypeError ... has no method 'find'


回答1:


The real answer is you shouldn't. A component should be agnostic of the outside world, and adding a dependency on the store breaks that concept. Really you should get the models beforehand (in the route, or controller, depending on the logic) and passing them into the component.

https://github.com/emberjs/data/blob/master/TRANSITION.md

In general, looking up models directly in a component is an anti-pattern, and you should prefer to pass in any model you need in the template that included the component.

Now that I've said that, just pass the store into the component. It lives on the routes and controllers, so when you create a component send in the store as one of the arguments, then you can access it using this.get('store')

{{auto-complete store=controller.store}}

or

{{auto-complete store=store}}

http://emberjs.jsbin.com/OxIDiVU/720/edit



来源:https://stackoverflow.com/questions/19969028/how-to-get-the-store-in-a-component-in-ember-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!