`

party_bid重构

    博客分类:
  • js
 
阅读更多

做完party_bid四张卡后,要进行重构,重构是为了让代码更容易理解,把代码放在该放的位置.重构后的代码,每个函数只做一件事,每个方法不超过15行,尽可能的减少内圈复杂度,将管理数据的模型抽到model里,也就是说model里实现所有数据的增删改查,controlle只向view提供指示性标志变量和数据源,controll不实现任何功能方法,只通过调用方法实现逻辑控制,尽可能的用underscore代替循环.下面讲一下我在重构过程中我遇到的一些问题.

1.举个例子,用_.find代替for循环,并抽成方法

Bid.activity_current_activity = function () {
    var action = JSON.parse(localStorage.getItem("activities"))
    return(  _.find(action, function (act) {
        return act.name == localStorage.current_activity
    }))       //找到当前的活动并返回,_.filter会返回所有符合的数组
}

 2.定义类方法

function Activity (name){
    this.name=name;
    this.activity_status='false';
    this.apply_list=[];
    this.bid_status='false';
    this.bid_list=[]
}
Activity.prototype.save_message=function(){  //prototype可以让我们向对象添加属性和方法
    var activities = JSON.parse(localStorage.getItem("activities")) || [];
    activities.unshift(this)   //把Activity压入activities
    localStorage.setItem("activities", JSON.stringify(activities))
}

 3.讲一下用的比较多的undersc0re里的_.findwhere

 _.findWhere(action,{name:localStorage.current_activity}).bid_status="true"  //找到当前的活动名,并对其中的bid_status赋值true,然后可以用localStorage存储

 4._.map的用法

_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });  //对数组中的元素遍历,会返回{3,6,9}

 5.通过function传值还可以把$scope抽出来抽成方法

Bid.judge_check_bid_price_bid_count = function ($scope) {
    if (!Bid.check_bid_price_bid_count()) {
        $scope.success = "false"
        $scope.fail = "true"          //通过传值可以把success的值传到页面,要善于用function的传值,会大大的提高效率
    }
}

 切忌函数的命名一定要做到见名知意,重构没有最好,只有更好,继续学习underscore的其它方法,简化代码

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics