跳至主要内容

Getting started with Angular 1.5 and ES6: part 5

Apply Container/Presenter pattern

If you have used React, you could be fimilar with Container/Presenter pattern.
The presenter component is responsive for rendering view and notifying event handlers to handle events.
The container component handles events, interacts with external resources, eg, in a React application, the container is the glue codes with Redux.
In this post, I just try to split component into small components by different responsibilities.
Go back to post detail component as an example.
The post details view includes three sections:
  • Post details
  • Comment list of this post
  • A Comment form used for adding new comment
We can create three components for this page.
  • PostDetailCard
  • PostCommentList
  • PostCommentForm
Replace post detail template with the following:
<post-detail-card post="$ctrl.post"></post-detail-card>
<post-comment-list comments="$ctrl.comments"></post-comment-list>
<post-comment-form on-save-comment="$ctrl.saveComment($event)"></post-comment-form>
post-detail-card shows the post detail.
post-detail-card.html:
<div class="page-header">
  <h1 class="text-xs-center text-uppercase text-justify">
    {{$ctrl.post.title}}
  </h1>
  <p class="text-xs-center text-muted">{{$ctrl.post.createdAt|date:'short'}}</p>
</div>
<div class="card">
  <div class="card-block">
    <p>
      {{$ctrl.post.content}}
    </p>
  </div>
  <div class="card-footer">
    back to <a href="#" ui-sref="app.posts">{{'post-list'}}</a>
  </div>
</div>
post-detail-card.component.js:
import template from './post-detail-card.html';

let postDetailCardComponent = {
  restrict: 'E',
  bindings: {
    post: '<'
  },
  template
};

export default postDetailCardComponent;
We use bindings here to bind expression, string, or callback methods to the controller of this component.
< means one-way binding, like most of modern frameworks, such as Angular 2, React etc. It receives the data from its parent component, but never sync changes to its parent when it is updated.
Lets have a look at CommentList.
post-comment-list.html:
<div class="card" ng-if="$ctrl.comments">
  <div class="card-block">
    <post-comment-list-item comment="c" ng-repeat="c in $ctrl.comments"></post-comment-list-item>
  </div>
</div>
post-comment-list.component.js:
import template from './post-comment-list.html';
import controller from './post-comment-list.controller.js';

let postCommentListComponent = {
  restrict: 'E',
  bindings: {
    comments: '<'
  },
  template,
  controller
};

export default postCommentListComponent;
It is very similar with post-detail-card component. But we use another component post-comment-list-item in the comment list iteration.
post-comment-list-item.html:
<div class="media">
  <div class="media-left media-top">
    <a href="#">
      <img class="media-object" src="../" alt="...">
    </a>
  </div>
  <div class="media-body">
    <h6 class="media-heading">{{$ctrl.comment.createdBy}} &bull; {{$ctrl.comment.createdAt}}</h6>
    <p> {{$ctrl.comment.content}}</p>
  </div>
</div>
post-comment-list-item.component.js:
import template from './post-comment-list-item.html';

let postCommentListItemComponent = {
  restrict: 'E',
  bindings: {
    comment: '<'
  },
  template
};

export default postCommentListItemComponent;
Now, move to comment-form component.
post-comment-form.html:
<div class="card">
  <div class="card-block">
    <form id="form" name="form" class="form" ng-submit="$ctrl.saveCommentForm()" novalidate>
      <div class="form-group" ng-class="{'has-danger':form.content.$invalid && !form.content.$pristine}">
        <!--<label class="form-control-label" for="content">{{'comment-content'}} *</label>-->
        <textarea class="form-control" type="content" name="content" id="content" ng-model="$ctrl.newComment.content" rows="8" required
          ng-minlength="10">
        </textarea>
        <div class="form-control-feedback" ng-messages="form.content.$error" ng-if="form.content.$invalid && !form.content.$pristine">
          <p ng-message="required">Comment is required</p>
          <p ng-message="minlength">At least 10 chars</p>
        </div>
      </div>
      <div class="form-group">
        <button type="submit" class="btn btn-success btn-lg" ng-disabled="form.$invalid || form.$pending">  {{'save'}}
        </button>
      </div>
    </form>
  </div>
</div>
post-comment-fom.component.js:
import template from './post-comment-form.html';
import controller from './post-comment-form.controller.js';

let postCommentFormComponent = {
  restrict: 'E',
  bindings: {
    onSaveComment: '&'
  },
  template,
  controller
};

export default postCommentFormComponent;
post-comment-form.controller.js:
class PostCommentFormController {
  constructor($scope) {
    'ngInject';

    this._$scope = $scope;
    this.newComment = {
      content: ''
    };
  }

  saveCommentForm() {
    this.onSaveComment({$event: this.newComment})
      .then(
        (res) => {
          this.newComment = {
            content: ''
          };
          this._$scope.form.$setPristine();
        }
      );
  }
}

export default PostCommentFormController;
In before components, we do not use controllers. In this Comment Form component, we need to call the callback method and wait for the result, and then clean the comment form when the comment was added successfully.
The comment data can be transfered via a $event object. Through this way, post-comment-form component itself does not handle the saving event, and just delegates it to post-detail component for further processing.
In the post-detail components, it receives $event data and processes it.
saveComment(event) {
console.log("saving comment...@");
let deferred = this._$q.defer();

this._Post.saveComment(this.id, event)
  .then((res) => {
    //refresh comments by post.
    console.log('saved comment.');
    this._Post.getCommentsByPost(this.id)
      .then((res) => {
        console.log('refresh comments list...');
        this.comments = res;
        this._toastr.success('Comment was added!');
        deferred.resolve(res);
      });
  });

return deferred.promise;
}
Register all new components in components/posts/index.js:
//...
import postDetailCardComponent from './post-detail-card.component';
import postCommentListComponent from './post-comment-list.component';
import postCommentListItemComponent from './post-comment-list-item.component';
import postCommentFormComponent from './post-comment-form.component';
//...
let postsModule = angular.module('posts', [commonSevices, uiRouter])
//...
  .component('postDetailCard', postDetailCardComponent)
  .component('postCommentList', postCommentListComponent)
  .component('postCommentListItem', postCommentListItemComponent)
  .component('postCommentForm', postCommentFormComponent) 
//... 
With this, all new added components(post-detail-card, post-comment-form, post-comment-list, post-comment-list-item) are only responsive for rendering view and triggering event handlers, and post-detail handles the input and output.

评论

此博客中的热门博文

AngularJS CakePHP Sample codes

Introduction This sample is a Blog application which has the same features with the official CakePHP Blog tutorial, the difference is AngularJS was used as frontend solution, and CakePHP was only use for building backend RESR API. Technologies AngularJS   is a popular JS framework in these days, brought by Google. In this example application, AngularJS and Bootstrap are used to implement the frontend pages. CakePHP   is one of the most popular PHP frameworks in the world. CakePHP is used as the backend REST API producer. MySQL   is used as the database in this sample application. A PHP runtime environment is also required, I was using   WAMP   under Windows system. Post links I assume you have some experience of PHP and CakePHP before, and know well about Apache server. Else you could read the official PHP introduction( php.net ) and browse the official CakePHP Blog tutorial to have basic knowledge about CakePHP. In these posts, I tried to follow the steps describ

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa