vendredi 31 juillet 2015

Simple boolean conditonal from AJAX (ember.js)

I'm trying to do something which must be really simple to accomplish in Ember.

I want to show a button in my template based on the boolean state of a property:

{{#if canFavoriteTag}}
  {{d-button action="favoriteTag" label="tagging.favorite" icon="star-o" class="admin-tag favorite-tag"}}
{{else}}
  {{d-button action="unFavoriteTag" label="tagging.unfavorite" icon="star-o" class="admin-tag favorite-tag tag-unfavorite"}}
{{/if}}

I have created a property called canFavoriteTag with a function which I want to return true or false to the template based on whether the user can favorite the tag or not:

export default Ember.Controller.extend(BulkTopicSelection, {

  canFavoriteTag: function() {

    const self = this;
    var ticker = this.get('tag.id');
    console.log('checking can fav stock:' + ticker);

    Discourse.ajax("/stock/get_users_favorite_stocks", {
          type: "GET",
        }).then(function(data) {

          var favable = true;

          for (var i = data.stock.length - 1; i >= 0; i--) {
            var stock = jQuery.parseJSON(data.stock[i]);
            if(ticker.toLowerCase() == stock.symbol.toLowerCase()) { console.log(ticker + ' is a favorite stock: ' + stock.symbol.toLowerCase()); favable = false; }
          }

          console.log(favable);
          return favable;

    });

  }.property('canFavoriteTag') <-- unsure about this?

...

When the page loads, the wrong button shows (always the "false" one).. I see in the console that the favable variable gets set to false when the ajax call completes, but the button never changes. How do I get it to show the right button based on the function? Do I need to use a promise? If so, how?

Appreciate any help or hints :) Thanks!




Aucun commentaire:

Enregistrer un commentaire