如何在ember的transcluded视图中访问组件属性?

时间:2015-01-27 10:21:21

标签: ember.js ember-data handlebars.js ember-components

我将一些html传递给ember中的组件。 html产生了。 但是,生成的html无法访问组件中定义的属性。但是,这些属性可以在组件模板上运行。

成分

import Ember from 'ember';

export default Ember.Component.extend({
  user: undefined,
  replyText: undefined,

  onInitialization: function(){
    this.set('replyText', '@' + this.user.get('username') + ' ');
  }.on("init"),

  remainingTweetChars: function () {
    var length = 140 - this.get('replyText').length;

    return length;
  }.property('replyText')

});

组件模板

{{remainingTweetChars}} {{!-- this works --}}

{{yield}}

使用html的组件用法,该组件使用上面的组件模板

{{#action-reply class="item-actionables__reply"
  user=user
}}

  <span>{{remainingTweetChars}}</span> {{!-- this does NOT works --}}
  <span>{{view.remainingTweetChars}}</span> {{!-- this does NOT works --}}
{{/action-reply}}

1 个答案:

答案 0 :(得分:2)

要解决此问题,您可以为组件分配viewName并使用它来引用所定义的任何属性。

实施例,

http://emberjs.jsbin.com/bihuzupogi/1/edit?html,js,output

<强> HBS

<script type="text/x-handlebars">
    <h2>Welcome to Ember.js</h2>
    <h3>Component in block form example accessing props</h3>

    {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="index">

  {{#test-comp propInTmpl="test-prop-in-tmpl" viewName="the-test-comp"}}
  <span style="color:gray">
  this is content of the block content <b>without</b> using <b>viewName</b>
   (<b>props:</b> {{propInTmpl}}, {{propInClass}})
  </span>
  <br/>
  <span style="color:gray">
  this is content of the block content using the <b>viewName</b>
   (<b>props:</b> {{view.the-test-comp.propInTmpl}}, {{view.the-test-comp.propInClass}})
  </span>
  {{/test-comp}}
  </script>

  <script type="text/x-handlebars" data-template-name="components/test-comp">

  <i>This is content of test-compo component template! (<b>props:</b> {{propInTmpl}}, {{propInClass}})</i>
  <br/>
  {{yield}}
  </script>

<强> JS

App = Ember.Application.create();

App.TestCompComponent = Em.Component.extend({
  propInClass:"test-prop-in-class"
});