Richard Knop
Richard Knop

Reputation: 83697

EmberJS - add method to view and call it

So I have added a method to HomeView like this:

App.HomeView = Ember.View.extend({
    isFailed: function () {
        console.log(this);
        return "FAILED" === this.get("state");
    }
});

In the HTML this is how the home template looks. As you can see I am calling the isFailed function inside a loop and for some reason, it is never called (nothing in the logs):

<script type="text/x-handlebars" id="home">
    <table>
        <thead>
        <tr>
            <th>ID</th>
            <th>Status</th>
            <th>Foo</th>
            <th>Bar</th>
        </tr>
        </thead>

        <tbody>

        {{#each}}
        <tr>
            <td>{{id}}</td>
            <td>
                {{#if isFailed }}
                FAILED
                {{/if}}
            </td>
            <td>bar</td>
            <td>foobar</td>
        </tr>
        {{/each}}

        </tbody>
    </table>
</script>

Any idea why the isFailed function is not being called?

jsfiddle: http://jsfiddle.net/dWxTn/2/

Upvotes: 0

Views: 43

Answers (1)

Simon Boudrias
Simon Boudrias

Reputation: 44589

Handlebars is a logicless template engine, it won't never execute code. It only use values and print them.

Here chances are that isFailed will always return truthy as it is a function.

To use it, use an Ember computed property

isFailed: function () {
    console.log(this);
    return "FAILED" === this.get("state");
}.property("state")

This way isFailed is going to be a Boolean updated automatically each time state changes

Upvotes: 1

Related Questions