Tuesday, April 15, 2014

Peticiones HTTP asíncronas con AngularJS

Esta es una forma de hacer peticiones Get asíncronas con AngularJS:

angular.module('TestApp').
controller('MainCtrl', ['Async', function (Async) {     
  Async.get(<URL>).then(
      function(data) {
          console.log("OK:",data);
      }, function(error) {
          console.log("ERROR:", error);
      });
}]).
// Servicio que encapsula operaciones asíncronas
factory('Async', ['$http', function($http) {     
  return {
      get: function(url) {
        var promise = $http.get(url).then(function (response) {
          // Devuelvo el body
          return response.data;
        });
           
        return promise;
      }
  };
}]);


He creado un servicio llamado Async con una función "get" que devuelve un objeto "promise". Este objeto promise es consumido de forma habitual por el llamante, en este caso un controlador llamado "MainCtrl"

Si la respuesta es correcta, se devuelve al controlador el body del mensaje http. En el caso particular que el body sea una cadena JSON, Angular la convierte automáticamente a un objeto.

Si la llamada acaba en error, se devuelve al controlador el objeto de error con el status y el mensaje de error, entre otra información.

Tuesday, April 8, 2014

Javascript prototypal inheritance with Object.create


An advantage that can turns out in disadvantage is that Javascript is a very expressive language. You can do something in very different ways. In this case I'll show a way to model inheritance using Object.create (ECMAScript 5).

In the following example, two objects are created: parent and child. These both objects are like "classes" in lenguajes with classical inheritance as Java. From those objects, I create two instances using Object.create: Pepe (the parent) and Pablo (the child). In this case, Pablo prototypically inherits from Pepe.


// In case of using IE 
if (typeof console === 'undefined') {
  console = {
  log: function(text) {
  alert(text);
  }
  }
}
    
// In case of using IE<10
if(typeof Object.create !== 'function') { 
  Object.create = function (o) { 
    function F() {}; 
    F.prototype = o; 
    return new F(); 
  }; 
}
    
// Helper to add properties to an object
function extend(obj, props) { 
  for(prop in props) { 
    if(props.hasOwnProperty(prop)) { 
      obj[prop] = props[prop]; 
    } 
  } 
}
    
    // Parent object
var parent = {
talk: function() {
console.log("I'm "+this.name);
},
work: function() {
console.log("I'm going to work");
},
init: function(name) {
this.name=name;
return this;
},
create: function(name) {
return Object.create(this).init(name);
}
};

// Child object
var child = Object.create(parent)
extend(child, {
work : function() {
    console.log("I can't work, I'm a child!");
}
});

// Parent instance
var pepe = parent.create("Pepe");

// Child instance
var pablo = child.create("Pablo");

pepe.talk(); // I'm Pepe
pepe.work(); // I'm going to work

pablo.talk(); // I'm Pablo
pablo.work(); // I can't work, I'm a child!