繁体   English   中英

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

[英]how to get the store in a component in ember.js

我是如何在一个组件内部处理商店的? 我正在尝试创建一个从商店返回结果的自动完成组件。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM