Chandler
Chandler

Reputation: 1078

How do I bind a handlebars variable to a promise in ember.js

In Ember.js I am trying to bind a handlebars conditional the outcome of a ember-data fetch that returns a promise.

I understand that the promise has a success call back, but I don't understand how to bind the result of that success to the value of the computed property. The value of the computed property always seems to be true because it returns the promise.

{{#if game.moreThanOnePlayer}}
  <span> it was true </span>
{{/if}}


App.Game = DS.Model.extend
  players: DS.hasMany 'App.Player'
  moreThanOnePlayer: (->

    promise = @get('players') #triggers ajax call that returns a promise

    promise.then(
    (players) -> #promise success call back
      return players.length > 1 #this is what I want the computed property value to be
    )

    #but the return value of the function is still a promise, which always evaluates to true.
    return promise
  ).property('players')

ember-data version: // Last commit: ef11bff (2013-08-26 20:54:06 -0700)

Upvotes: 1

Views: 1469

Answers (2)

jonne
jonne

Reputation: 325

I just managed to solve a very similar problem by wrapping part of the code in an Ember.run.once(...) block. I split the property I used in handlebars and the code that watches for changes. In your case I would try something like:

App.Game = DS.Model.extend
  players: DS.hasMany 'App.Player'
  moreThenOnePlayer: DS.attr 'boolean'
  playersUpdated: (->
    promise = @get('players')
    g = @
    promise.then(
      (players) ->
        Ember.run.once ->
          g.set 'moreThenOnePlayer', players.length > 1
    )
  ).observes('players')

Upvotes: 0

dierbro
dierbro

Reputation: 156

You should load the data in the Route and make moreThanOnePlayer a computed property.

See http://jsbin.com/AJUWOJi/1/edit for an example.

Upvotes: 0

Related Questions