跳至主要内容

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.

评论

此博客中的热门博文

Build a Reactive application with Angular 5 and Spring Boot 2.0

I have created a post to describe Reactive programming supports in Spring 5 and its subprojects, all codes of this article are updated the latest Spring 5 RELEASE, check spring-reactive-sample under my Github account.
In this post, I will create a simple blog system, including:
A user can sign in and sign out.An authenticated user can create a post.An authenticated user can update a post.Only the user who has ADMIN role can delete a post.All users(including anonymous users) can view post list and post details.An authenticated user can add his comments to a certain post. The backend will be built with the latest Spring 5 reactive stack, including:
Spring Boot 2.0, at the moment the latest version is 2.0.0.M7Spring Data MongoDB supports reactive operations for MongoDBSpring Session adds reactive support for WebSessionSpring Security 5 aligns with Spring 5 reactive stack The frontend is an Angular based SPA and it will be generated by Angular CLI.
The source code is hosted on Github, …

Activating CDI in JSF 2.3

Activating CDI in JSF 2.3 When I upgraed my Java EE 7 sample to the newest Java EE 8, the first thing confused me is the CDI beans are not recoganized in Facelects template in a JSF 2.3 based web applicaiton, which is working in the development version, but in the final release version, they are always resolved as null. I filed an issue on Mojarra and discussed it with the developers from communities and the JSF experts.
According to the content of README, In a JSF 2.3 application, to activate CDI support, declaring a 2.3 versioned faces-config.xml and adding javax.faces.ENABLE_CDI_RESOLVER_CHAIN in web.xml is not enough, you have to declare @FacesConfig annotated class to enable CDI.
Here is the steps I created a workable JSF 2.3 applicatoin in Java EE 8.
Create a Java web application, this can be done easily by NetBeans IDE, or generated by Maven archetype, for exmaple.
$ mvn archetype:generate -DgroupId=com.example -DartifactId=demo -DarchetypeArtifactId=maven-archetype-w…

JSF 2.3:Websocket support

Websocket support One of the most attractive features is JSF 2.3 added native websocket support, it means you can write real-time applications with JSF and no need extra effort.
To enable websocket support, you have to add javax.faces.ENABLE_WEBSOCKET_ENDPOINT in web.xml.
<context-param> <param-name>javax.faces.ENABLE_WEBSOCKET_ENDPOINT</param-name> <param-value>true</param-value> </context-param> Hello Websocket Let's start with a simple example.
@ViewScoped@Named("helloBean") publicclassHelloBeanimplementsSerializable { privatestaticfinalLoggerLOG=Logger.getLogger(HelloBean.class.getName()); @Inject@PushPushContext helloChannel; String message; publicvoidsendMessage() { LOG.log(Level.INFO, "send push message"); this.sendPushMessage("hello"); } privatevoidsendPushMessage(Objectmessage) { helloChannel.send(""+ message +" at &…