跳至主要内容

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.
发表评论

此博客中的热门博文

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 thePostentity 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 converter In this example…

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 addhibernate-enversas 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@Auditedannotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If@Auditedannotation is placed on a property, this property can be tracked.

Spring Data Mongo: bridge MongoDB and Spring

Spring Data Mongo: bridge MongoDB and SpringMongoDBis one of the most popular NoSQL products, Spring Data Mongo(Maven archetype id is spring-data-mongodb) tries to provides a simple approach to access MongoDB. Configuration Add the following code fragments in your Spring configuration. <!-- Mongo config --> <mongo:db-factory id="mongoDbFactory" host="localhost" port="27017" dbname="conference-db" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> </bean> <mongo:repositories base-package="com.hantsylabs.example.spring.mongo" /> Firstly, declare aDbFactorywhich is responsible for connecting to the MongoDB server. Then, register theMongoTemplateobject which envelop the data operations on MongoDB. Lastly addmongo:repositorieswith an essentialbase-packageattribute, Spring will discovery your d…