Javascript ajax library supporting global events -


which ajax library should use react/flux app? need globally handle errors (e.g. automatically logout , redirect login if 401; similar $http service in angular) , use promises.

the way i'm doing combination of 3 libraries:

  1. reflux.js
  2. bluebird
  3. jquery

webutils.js

var promise = require('bluebird');  module.exports = {   makeapicall: function() {     return promise.resolve($.get("http://makeyourapicall"));   } }; 

actions.js:

var reflux = require('reflux'); var webutils = require('web-utils.js');  var actions = reflux.createactions({   getdatafromserver: { asyncresult: true }  });  actions.getdatafromserver.listenandpromise(webutils.makeapicall);  module.exports = actions; 

explanation:

  • the asyncresult: true in createactions call creates "nested/asynchronous action" can listen to. more here
  • the listenandpromise function hooks promise nested completed , failed callbacks based on result

you can consume nested actions this:

actions.getdatafromserver.complete.listen(res => console.log('success', res));  actions.getdatafromserver.failed.listen(err => console.log('failed', err)); 

in sense can implement universal error handler hooking .failed events.

reflux-error-handler.js

var _ = require('lodash'); var reflux = require('reflux'); var notificationstore = require('../stores/notificationstore');  /**  * overall error handler async actions  * @param err  */ function handleerror(err) {   console.error('encountered error:', err);   notificationstore.createerrornotification(err); }  /**  * loops on refluxactions , attaches error handler async actions  * @param refluxactions {object} hash of reflux actions ot generate  * @constructor  */ var refluxerrorhandler = function(refluxactions) {   _.foreach(refluxactions, func => {     if(func.failed) {       func.failed.listen(handleerror);     }   });   return refluxactions; };  module.exports.wraprefluxactions = refluxerrorhandler; 

to use in actions.js:

var reflux = require('reflux'); var webutils = require('web-utils.js'); var refluxerrorhandler = require('reflux-error-handler.js');  var actions = reflux.createactions({   getdatafromserver: { asyncresult: true }  });  actions.getdatafromserver.listenandpromise(webutils.makeapicall);  module.exports = refluxerrorhandler(actions); 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -