Ember:在ember组件中丢失了上下文

时间:2014-07-03 09:23:34

标签: ember.js handlebars.js ember-cli

我遇到了Ember的问题,虽然不太确定问题出在哪里,无论是在Handlebars还是Ember组件中。

问题是当控制器对象上下文传入ember组件时,作为参数,上下文未定义。但是,在组件之前的把手模板中记录对象,显示正确的对象(请参阅索引和组件/组件按钮模板)。

模板

<script type="text/x-handlebars" data-template-name="application">
    <h1>Fiddling</h1>
    {{outlet}}
</script>

<script type="text/x-handlebars" data-template-name="index">
  {{#each sections}}
    {{#each buttons}}
        {{log 'source in template' ../source}}
        {{component-button source=../source options=this}}
    {{/each}}
  {{/each}}
</script>

<script type="text/x-handlebars" data-template-name="components/component-button">
    {{log 'source in component' source}}
    <button {{action 'options.action'}}>{{options.label}}</button>
</script>

应用

App = Ember.Application.create( {} );

/**
 * Component: Button
 */
App.ButtonComponent = Ember.Component.extend( {

  tagName: 'button',

  click: function click() {
    this.get( 'source' ).send( this.get( 'options.action' ) );
  }

} );

/**
 * Controller: Application
 */
App.IndexController = Ember.ObjectController.extend( {

  sections: Ember.A(),

  actions: {
    doSomething: function() {
      window.console.log( 'hooray!' );
    }
  },

  setup: function setup() {
    var source = this;

    var section = Ember.Object.create( {
      source: source,
      buttons: Ember.A( [
        Ember.Object.create( {
          label: 'Do something!',
          action: 'doSomething'
        } )
      ] )
    } );

    this.sections.pushObject( section );

  }.on( 'init' )

} );

App.IndexRoute = Ember.Route.extend( {
  model: function() {
      return { name: 'foo' };
  }
} );

See fiddle

1 个答案:

答案 0 :(得分:0)

不要在每个循环中引用../source,而是执行以下操作:

<script type="text/x-handlebars" data-template-name="index">
    {{#each section in sections}}
        {{#each section.buttons}}
            {{log 'source in template' section.source}}
            {{component-button source=section.source options=this}}
        {{/each}}
    {{/each}}
</script>

在第一个中,定义了每个'section',它可以在嵌套的每个语句中用于引用该部分。