简体   繁体   中英

how to pass parameters to ember component

This ember component template:

<script type="text/x-handlebars" id="components/blog-post">
  <h1>Component: {{title}}</h1>
  <p>Lorem ipsum dolor sit amet.</p>
</script>

This is the component code:

App.BlogPostComponent = Ember.Component.extend({
    // how can i access the title property here? (this.title doesn't work)
    // also this.get('title') throws error: undefined is not a function
    computedProp: 'width' + this.title
});

And it's usage:

{{blog-post title=title body=body}}

I can access the title property from the component template easily with {{title}} .

How can i access the title property from within the component code, App.BlogPostComponent .

Also is there an easy way to ember properties in handlebars such as:

<h1 style="width: {{percent}}%">

Edit :

When I do this as suggested:

App.BlogPostComponent = Ember.Component.extend({
  computedProp: function () {
    return 'width' + this.get('title');
  }.property('title')
});

I get the error:

Uncaught Error: Assertion Failed: Attributes must be numbers, 
strings or booleans, not function () {
            return 'width:' + 50 + '%';
        } 

Edit2: Ok the reason for the error is omitting .property('title') at the end of function definition. It's fixed now.

this.get should work just fine, the problem is that you are not calling it in object context. The correct way to define computed property would be:

App.BlogPostComponent = Ember.Component.extend({
  computedProp: function () {
    return 'width' + this.get('title');
  }.property('title')
});

Things like <h1 style="width: {{percent}}%"> are impossible right now, you should use bind-attr helper + computed property for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM