Pros / cons of using events to a large extent for synchronizing controllers in complex Angular applications

Can someone give me tips on the pros and cons of using events to a large extent to keep different parts of an Angular application in sync with each other?

I am considering using a series of events and event listeners to combine SPAs with several parallel and nested views provided by Angular ui-router . SPA layout can be similar to gmail, where there are logically separate areas of the screen (left area with a list of mail folders, top navigation bar, presentation of the main details, etc.).

I considered ways to synchronize all controllers with models, which all of them must access at the same time. When a model is updated in the top view, if any of this model is displayed in the main view, I want the main view to notice the change and update its view accordingly.

I use services to exchange models between controllers, as it is considered best practice, but there are problems with this approach, which are discussed in detail in this issue .

A possible solution for this is to use Angular $broadcastand .$on('event, fn())so that dispatchers notice when the service they care about has updated the data.

Problems:

  • ( , ). , , .
  • ( $scope ..).

    $broadcast/$emit , , SO / - .

  • ( / OO ). , : () , Angular .service , , , , : Event wiring diagram

( ), 5- , .

- , / ?

, ... , .

+4
3

Pros?

  • angular Knockout/Durandal?

?

  • angular Knockout/Durandal?

, : .

.

- OO. , angular , .

. User , , . User.password .

, . . . .

+2

, , :

( ) , viewmodel , :

$scope.errors = myModel.update($scope.formFields);

, :

$scope.$watch('formFields', function (values) {
    $scope.errors = myModel.validate(values);
});
$scope.submit = function () {
    $scope.errors = myModel.update($scope.formFields);
    if ($scope.errors.length < 0) {
        $scope.formFields = {};
        $scope.showForm = false; 
    }
};

, .

:

var items = {};
return {
    'getItems': function () {
        return items;
    }
};

:

$scope.myList = myListModelService;

:

<li ng-repeat="item in myList.getItems()">

, / ($scope.myList.getItems().push(newItem);). , : " , - API- " () , : " - ". , , , , - , :).

, getter Angular $watch, .

+2

-

There are only three events in the entire AngularJS structure: Fixed ($ includeContentRequested, $ includeContentLoaded, $ viewContentLoaded) and seven events broadcast ($ locationChangeStart, $ locationChangeSuccess, $ routeUpdate, $ routeChangeStart, $ routeChangeSuccess, $ routeChangeError, $ destroy). As you can see, scope events are used very sparingly, and we need to evaluate other options (mostly two-way data binding) before sending custom events.

0
source

Source: https://habr.com/ru/post/1524164/


All Articles