【问题标题】:how to get the store in a component in ember.js如何在 ember.js 中的组件中获取商店
【发布时间】:2013-11-14 03:34:00
【问题描述】:

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

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'

【问题讨论】:

    标签: javascript ember.js nullreferenceexception


    【解决方案1】:

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

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

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

    既然我已经说过了,只需将 store 传递给组件。它存在于路由和控制器上,因此当您创建一个组件作为参数之一发送到商店时,您可以使用this.get('store') 访问它

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

    {{auto-complete store=store}}
    

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

    【讨论】:

    • 那个过渡文件绝对是我需要的。谢谢谢谢!
    • 所以组件不能创建记录?或者对它们进行服务器端验证?
    • 他们可以,不管是不是推荐的模式,一般都不会。
    • 我必须使用 this.store。
    猜你喜欢
    • 2022-11-25
    • 2019-10-29
    • 2011-02-12
    • 2016-01-13
    • 2013-05-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多