+1

Some tips may you need ....

Introduce

When getting started with Angular it can be a bit overwhelming to try and make sense of all the different tools and types of components that are available to us.

A very popular example of this are Services and Factories: they seem so similar yet they both exist for some reason. You’re trying to understand whether there’s really any difference. No one wants to pick the “wrong one” or “make the wrong choice”.

Factories vs. Services

First, right off the bat I’ll say they’re pretty much equivalent. Why do we have them both, then? That’s for the gods of Angular to know. They both allow us to create an object that can then be used anywhere in our app.

Most important is to realize that both are singletons in your app, even though the name “factory” might imply differently.

Essentially, factories are functions that return the object, while services are constructor functions of the object which are instantiated with the new keyword.

To the users of our services and factories it all looks the same. This code below would be written the same regardless of which was used:

angular.module('app').controller('TheCtrl', function($scope, SomeService) {
    SomeService.someFunction();
});

angular.module('app').factory('SomeService', function() {
    return {
        someFunction: function() {}
    };
});
angular.module('app').controller('TheCtrl', function($scope, SomeService) {
    SomeService.someFunction();
});

angular.module('app').service('SomeService', function() {
    this.someFunction = function() {};
});

$emit, $broadcast and $on

AngularJS provides $on, $emit, and $broadcast services for event-based communication between controllers.

emit-broadcast.png

$scope.$emit up, $scope.$broadcast down

Using $scope.$emit will fire an event up the $scope. Using $scope.$broadcast will fire an event down the $scope. Using $scope.$on is how we listen for these events

app.controller('parentCtrl',
  function parentCtrl ($scope) {
  $scope.$broadcast('parent', 'Some data'); // going down!
});
app.controller('childCtrl',
  function childCtrl ($scope) {
  $scope.$on('parent', function (event, data) {
    console.log(data); // 'Some data'
  });
});
app.controller('parentCtrl',
  function parentCtrl ($scope) {
  $scope.$on('child', function (event, data) {
    console.log(data); // 'Some data'
  });
});

app.controller('childCtrl',
  function childCtrl ($scope) {
  $scope.$emit('child', 'Some data'); // going up!
});

Noted: the $broadcast() algorithm, in AngularJS, is heavily optimized; AngularJS will only traverse areas of the scope tree that are known to have bound-listeners for a certain event type. So, while the $rootScope.$emit() approach is faster

$scope.$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.

app.controller('childCtrl',
  function childCtrl ($rootScope) {

  $rootScope.$on('rootScope:emit', function (event, data) {
    console.log(data); // 'Emit!'
  });

  $scope.$on('rootScope:broadcast', function (event, data) {
    console.log(data); // 'Broadcast!'
  });

  $rootScope.$on('rootScope:broadcast', function (event, data) {
    console.log(data); // 'Broadcast!'
  });

});

Noted: If there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes but you cannot emit your event. You can emit your event only when you have parent-child relation and event propagation is initiated by child. However, $emit can fire an event only for all $rootScope.$on listeners.

Difference between promise and callback

Callbacks

Callbacks are commonly used when you have an asynchronous operation that should notify the caller about its’ completion:

var toppings = {cheese: true, bacon: true};

function orderPizza(data, done) {
  // send info to server (which might take a few milliseconds to complete)
  xhr({
    uri: '/order/submit',
    data: data,
    complete: function(status, msg, response) {
      if (status !== 200) {
        // notify about error
        done(new Error(status +': '+ msg));
      }
      // notify about success
      done(null, response);
    }
  });
}

// the method "showOrderStatusDialog" will be called after we get the response
// from the server
orderPizza(toppings, showOrderStatusDialog);

function showOrderStatusDialog(err, response) {
  if (err) {
    showOrderFailure(err);
  } else {
    showOrderSuccess(response);
  }
}

Callbacks are great for cases where you have an action that triggers a direct reaction (eg. animation, ajax, batch processing).

Promises

A promise is a proxy for a value not necessarily known at its creation time. With promises, rather than an asynchronous call accepting a callback, it instead returns a promise. The calling code can then wait until that promise is fulfilled before executing the next step. To do so, the promise has a method named then, which accepts a function that will be invoked when the promise has been fulfilled. As an example, the following is the above code rewritten using promises:

function orderPizza(data) {
  // the xhr in this case returns a promise and handle the error logic
  // internally; it shifts the complexity to the xhr implementation instead
  // of spreading it through your app code
  return xhr({
    uri: '/order/submit',
    data: data
  });
}

// first callback of `then` is success, 2nd is failure
orderPizza(toppings).then(showOrderSuccess, showOrderFailure);

There are 2 really cool things about promises:

  1. They are only resolved once;

  2. Then method returns another promise and you can return data from the callback to map the value received by the next callback in the chain;

Since promises are only resolved once they can be used for smart caching or for cases where you might have multiple calls trying to execute same action (which should only happen once).

Ref :

https://www.quora.com/Whats-the-difference-between-a-promise-and-a-callback-in-Javascript https://www.sitepoint.com/premium/books/angularjs-novice-to-ninja/preview/angularjs-services-factories-and-providers-791b6d5


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí