emberjs - 组件助手的重构

时间:2015-10-31 07:01:50

标签: ember.js

我正在从ember 1.7.1迁移一些代码,然后我创建了自己的组件助手,然后才有一个把手助手的形式:

Ember.Handlebars.registerHelper('renderComponent', function(contextPath, propertyPath, options) {
  var context, helper, property;
  context = Ember.Handlebars.get(this, contextPath, options);
  property = Ember.Handlebars.get(this, propertyPath, options);
  helper = Ember.Handlebars.resolveHelper(options.data.view.container, property.component);
  options.contexts = [];
  options.types = [];
  property.bindings.forEach(function(binding) {
    options.hash[binding] = binding;
    options.hashTypes[binding] = "ID";
    options.hashContexts[binding] = context;
  });

  return helper.call(context, options);
});

帮助器的调用如下:

{{#each list as |item|}}
  {{#each column in columns}}
    <td>
      {{renderComponent item column}
    </td>
   {{/each}}
{{/each}}

并且会从这样的配置中创建组件:

App.IndexController = Ember.Controller.extend({
  columns: Ember.A([
   {
      heading: "Heading",
      binding: "name",
      route: "company"
    },
    {
      heading: "Address",
      binding: "address"
    },
    {
      heading: 'full',
      component: 'full-contact',
      bindings: ['name', 'address']
    }
  ])
});

如何使用组件助手实现相同的功能?

我是否正在考虑将参数和绑定传递给组件帮助器?怎么做的?

1 个答案:

答案 0 :(得分:1)

在看到您的更新和评论后,您走在了正确的轨道上。组件助手如您所述:

{{component 'name' paramName='paramValue' otherParam='otherValue'}}

当然,每个财产都可以绑定

{{component boundComponentName paramName=boundParamValue otherParam=boundOtherValue}}

看一下我创建的Ember Twiddle来说明。查找application.hbs文件和my-component template/component.js文件