【问题标题】:How do I access component properties in a transcluded view in ember?如何在 ember 的嵌入视图中访问组件属性?
【发布时间】:2015-01-27 10:21:20
【问题描述】:

我正在将一些 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}}

【问题讨论】:

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


    【解决方案1】:

    要克服这个问题,您可以将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"
    });
    

    【讨论】:

    • 感谢@melc,因为 ember 2.0(猜想他们会在下一个版本 1.10 中这样做)正在弃用 viewscomponents。我想知道关键字view 是否会保留。有没有其他办法?
    • @ahmed 你能提供说明这一点的资源吗?我没注意到。该解决方案基于这样一个事实,即包含视图或组件将能够通过其父视图可用的 viewName 属性访问自身。因此,只要可以访问父视图,这将起作用。我认为总会有一种方法可以访问父视图,所以不会有问题。
    • @ahmed 在 ember 2.0 中,您将能够从组件内部产生值。见:emberjs.jsbin.com/gefahulavi/1/edit
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多