Search code examples
javascriptember.jshandlebars.jsdiscourse

Get list of badges in Discourse by accessing Ember.ArrayController from javascript outside of handlebars template


In Ember.js i know I can using the Ember.ArrayController to access a specific collection of data, like the example from the ember website:

MyApp.listController = Ember.ArrayController.create();

$.get('people.json', function(data) {
  MyApp.listController.set('model', data);
});

and access it in handlebars like this:

{{#each person in MyApp.listController}}
  {{person.firstName}} {{person.lastName}}
{{/each}}

Although, what I want to do is access the this in javascript? More specifically in Discourse, getting the badges for a user. The user-badges.js.es6 controller:

export default Ember.ArrayController.extend({
  sortProperties: ['badge.badge_type.sort_order', 'badge.name'],
  orderBy: function(ub1, ub2){
    var sr1 = ub1.get('badge.badge_type.sort_order');
    var sr2 = ub2.get('badge.badge_type.sort_order');


    if(sr1 > sr2) {
      return -1;
    }

    if(sr2 > sr1) {
      return 1;
    }

    return ub1.get('badge.name') < ub2.get('badge.name') ? -1 : 1;
  }
});

How can I get this list of badges for a user? Calling the Discourse.UsersBadges ArrayController does not seem to work.

   import UserBadges from 'discourse/controllers/user-badges';
   for(var badge in UserBadges){
      console.log(badge);
   }

I'm not sure if I'm running into a problem understanding how EmberJS is suppose to work or how Discourse has been designed to work.


Solution

  • I found that I was approaching the problem the wrong way and that I should use a promise to get the user badge like this:

    Discourse.UserBadge.findByUsername(Discourse.User.current().username).then(function(result) {
          result.forEach(function(entry) {
              console.log(entry.badge.name);
          }
       );
    });
    

    Although, now I have a new problem in which I need to load this information prior to the view loading. The promise does it asynchronously which will not load the data in time.