[AngularJS] Isolate State Mutations in Angular Components

本文介绍了一种在Angular中管理状态的简单技术,通过组件生命周期钩子隔离状态变更,特别是处理如表单等需要进行可变操作的情况。文章通过一个书签组件的例子展示了如何创建专门用于更新书签的组件,并在该组件内部复制原始数据,从而实现状态的隔离变更。

Managing state is one of the hardest things to do in any application. Angular 2 tackles this problem by making it easy to implement a reactive, uni-directional data flow that favor immutable operations. We are moving in the right direction in Angular 1 by moving our state and logic to models but invariably this raises a question. If we are moving to an immutable world, how do you manage mutable operations like forms in Angular? In this lesson, we are going to learn a surprisingly simple technique to isolate state mutations within a component using component lifecycle hooks.

 

For example you have a bookmark component, and inside the component, you want to update the bookmark. The solution is you create a component just for update bookmark.

<div class="bookmarks">
    <div ng-repeat="bookmark in bookmarksListCtrl.bookmarks | filter:{category:bookmarksListCtrl.getCurrentCategory().name}">
        <button type="button" class="close" ng-click="bookmarksListCtrl.deleteBookmark(bookmark)">&times;</button>
        <button type="button" class="btn btn-link" ng-click="bookmarksListCtrl.editBookmark(bookmark)">
            <span class="glyphicon glyphicon-pencil"></span>
        </button>
        <a href="{{bookmark.url}}" target="_blank">{{bookmark.title}}</a>
    </div>
    <div ng-if="bookmarksListCtrl.getCurrentCategory()">
        <button type="button" class="btn btn-link"
            ng-if="!bookmarksListCtrl.currentBookmark"
            ng-click="bookmarksListCtrl.createBookmark()">
            <span class="glyphicon glyphicon-plus"></span>
            Create Bookmark
        </button>
    </div>
    <save-bookmark
        ng-if="bookmarksListCtrl.currentBookmark"
        bookmark="bookmarksListCtrl.currentBookmark"
        save="bookmarksListCtrl.onSave(bookmark)"
        cancel="bookmarksListCtrl.reset()">
    </save-bookmark>
</div>

 

And inside the save-bookmark component, you can copy the original data, and modify on the copy data:

class SaveController {
  $onChanges() {
    this.editedBookmark = Object.assign({}, this.bookmark);
  }
}

export default SaveController;

This can isolate the component state muataion. 

转载于:https://www.cnblogs.com/Answer1215/p/5853999.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值