1

我在使用 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' };
  }
} );

见小提琴

4

1 回答 1

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>

首先定义了每个“部分”,可以在嵌套的每个语句中使用它来引用该部分。

于 2014-09-28T16:46:54.630 回答