如何在 Ember.js 中的组件中获取存储

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

本文关键字:组件 获取 存储 js Ember      更新时间:2023-09-26

我到底如何掌握组件内部的存储?我正在尝试创建一个从商店返回结果的自动完成组件。

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);
    }
});

这是我的公司模型

App.Company = DS.Model.extend({
  name: DS.attr('string'),
  created_at: DS.attr('date'),
  updated_at: DS.attr('date'),
  people: DS.hasMany('person')
});

我试过:

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

我总是得到一个Uncaught TypeError ... has no method 'find'

真正的答案是你不应该。 组件应该与外部世界无关,添加对存储的依赖关系会破坏该概念。 实际上,您应该事先获取模型(在路由或控制器中,具体取决于逻辑)并将它们传递到组件中。

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

通常,直接在组件中

查找模型是一种反模式,您应该更愿意在包含该组件的模板中传入所需的任何模型。

现在我已经说过了,只需将存储传递到组件中即可。 它位于路由和控制器上,因此当您创建组件时,将存储中的组件发送作为参数之一,然后可以使用this.get('store')

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

{{auto-complete store=store}}

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