mardi 17 novembre 2015

How to instantly change between the actions of a same link without refreshing the page? Creating a FB like feature

I am building a 'Watch this deal' functionality, which is similar to FB 'like' feature.

Here is the scenario:

There is an icon beside every deal which will enable the current user to 'watch' or 'not watch' the deal. The actions are completed and working and changes on the UI is also working fine. The problem is, when I click on that icon, I become a watcher of the deal but the icon doesn't change. I have to refresh the page to see that change.

controller:

actions:{
   // add and remove watchers

addToWatcher: function(deal) {
    var _this = this;
    var currentUser = this.get('currentUser');
    deal.get('watchers').addObject(currentUser);
    deal.save().then(function () {
      Ember.get(_this, 'flashMessages').success("You are now watching");
    }, function() {
      // Ember.get(_this, 'flashMessages').danger('apiFailure');
    });
},

removeWatcher: function(deal) {
    var _this = this;
    var currentUser = this.get('currentUser');
    deal.get('watchers').removeObject(currentUser);
    deal.save().then(function () {
      Ember.get(_this, 'flashMessages').success("You are now watching");
    }, function() {
      // Ember.get(_this, 'flashMessages').danger('apiFailure');
    });
}
}

views:

      {{#if (check-watcher deal currentUser.id)}}
         <i class="fa fa-2x sc-icon-watch watched" {{action 'removeWatcher' deal}} style="padding: 5px 10px;"></i><br>
      {{else}}
         <i class="fa fa-2x sc-icon-watch" {{action 'addToWatcher' deal}} style="padding: 5px 10px;"></i><br>
      {{/if}}

Here check-watcher is a helper I wrote to check if the deal is being watched by the current user. If it is, the icon will be Red and clicking on it again will trigger 'removeWatcher' action. If not, icon will be black and clicking on it will make user watch the deal.

So, how to make the change in UI happen between adding and removing watchers without refreshing the page?




Aucun commentaire:

Enregistrer un commentaire