Frank Jensen
Frank Jensen

Reputation: 367

Ember template renders function as string

I'm new to ember and got a problem with a template.

My route

import Ember from 'ember';

import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  model: function(params) {

    var pageNum   = params.page || 1,
        pageRows  = 8;

    return this.store.find('account', {
      page: pageNum,
      rows: pageRows
    });
  },

  setupController: function(controller, model) {
    controller.set('model', model);
    controller.set('greeting', 'Hello World');
  }
});

My Controller

import Ember from 'ember';

export default Ember.ArrayController.extend({
  contentLength: function() {
    // console.log(this);
    // console.log('length: ' + this.get('content').length);
    // return this.get('content').length;
    return 'Test string';
  },

  actions: {}
});

Template

{{ greeting }}
{{ contentLength }}

The {{ greeting }} gets rendered correctly. But {{ contentLength }} gets rendered out as a string function..

Hello World function () { // console.log(this); // console.log('length: ' + this.get('content').length); // return this.get('content').length; return 'Test string'; }

Anyone who can help me solve this issue?

Thanks

Upvotes: 1

Views: 167

Answers (2)

MrVinz
MrVinz

Reputation: 874

You need to add .property() at the end of the contentLength function in order to display it in a template:

import Ember from 'ember';

export default Ember.ArrayController.extend({
  contentLength: function() {
    // console.log(this);
    // console.log('length: ' + this.get('content').length);
    // return this.get('content').length;
    return 'Test string';
  }.property(),

  actions: {}
});

If you want the property to update whenever another property of your controller changes simply add it as a "parameter" of your property like this .property("thepropertytoobserve") and the length property of an arrayController is already aviable as {{length}} in the template.

Have a look at the doc for more details on computerd properties.

Upvotes: 1

Andrew Hacking
Andrew Hacking

Reputation: 6366

You can just use {{ length }} in your template as ArrayControllers already have that property.

The reason your contentLength function is not doing what you want is because it is not a computed property. You need to either use Ember.computed(function() { ..}) or append .property(...) to your contentLength function.

Eg:

contentLength: function() {
  return this.get('content.length');
}.property('content.length')

Upvotes: 1

Related Questions