【问题标题】:Pass function to an Ember component将函数传递给 Ember 组件
【发布时间】:2015-07-03 04:04:55
【问题描述】:

是否可以将函数传递给组件?我正在尝试将我的代码从视图移到组件上,以保持我的 Ember 应用程序向前发展(请参阅here),并且我在整个站点中都使用了一堆常用功能。我不确定如何从组件中调用它们。我在旧代码中将它们放在自己的控制器中,但我听说将控制器传递给组件是草率或不明智的。

例如在一个组件车把文件中,我正在考虑这个:

{{a-cool-component 
  property1=someValue
  function1=controllers.utils.doSomethingRepetitious 
}}

所以在我的组件 javascript 代码中我可以做这样的事情......

FacetListItemComponent = Ember['default'].Component.extend({
  property1: null
  property2: null
  function1: null 
  didInsertElement: function() {
    //... do stuff here
    this.set('property2', this.function1(this.get('property1')));
  }
);
exports['default'] = FacetListItemComponent;

我在我正在构建的组件中尝试了它,但 function1 遇到了 undefined

有什么建议吗?

我在 Ember-CLI 0.2.7 上使用 Ember 1.11

布莱恩

【问题讨论】:

  • 这是一个巨大的代码气味。你要传入的这个函数是做什么的?

标签: javascript ember.js


【解决方案1】:

您应该使用get(),并且不需要在组件上设置function1: null

//component
MyExComponent = Ember.Component.extend({
  didInsertElement: function(){
    var fun = this.get('function1');
    fun()
  }
})

//other component

MyOtherComponent = Ember.Component.extend({
  function1: function(){
    alert('hello');
  }
})

//other component template

{{my-ex
  function1=function1}}

【讨论】:

  • 这非常有效。它肯定会让我远离传递控制器的“代码气味”,并使我能够有效地重用代码。谢谢!
  • 这里要指出,这样做,函数会在窗口范围内执行,而不是父对象。 AKA 你的this 将是窗口。
  • 你可以使用一个计算属性,它会返回函数。示例:function1: Ember.computed(function() { return Ember.run.bind(this, this._function1) }) this 将保留 this 的上下文
  • 您能否澄清这在 Route.extend 和组件之间是否有效?我想在我的路由中使用组件并为路由定义回调,然后在组件内执行回调。在路由和组件之间使用此示例时,我遇到了同样的错误。
猜你喜欢
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 2020-07-28
  • 2019-07-02
  • 2017-10-10
  • 2018-08-29
  • 2019-06-25
  • 1970-01-01
相关资源
最近更新 更多