如何重构冗余代码以启动和更新?

时间:2014-10-23 05:43:50

标签: javascript angularjs

以下是我在AngularJS中的控制器代码。

var dcApp = angular.module("dcApp", ["dcApp.services"])


dcApp.controller("filterController",["$scope", "filterService",
    function ($scope, filterService) {
        var filterSentData = {
            specie: "all",
            cellinfo: "all",
            factor: "all",
            hideincomplete: "show",
            keyword: "",
            clicked: null,
            page: 1
        }
        filterService.setFilterSentData(filterSentData)
        filterService.request().success(function (data, status) {
            $scope.species = data.species
            $scope.cellinfos = data.cellinfos
            $scope.factors = data.factors
            $scope.datasets = data.datasets
        })

        $scope.setFilter = function(key, content) {
            filterSentData[key] = content
            filterService.setFilterSentData(filterSentData)
            filterService.request().success(function (data, status) {
                $scope.species = data.species
                $scope.cellinfos = data.cellinfos
                $scope.factors = data.factors
                $scope.datasets = data.datasets
            })

        }


    }]);

可以找到,filterService.setFilterSentData(filterSentData)filterService.request().success代码段使用了两次。一个用于启动,另一个用于在setFilter更改过滤器时进行必要的更新。有没有人有关于重构代码的好方法的想法?

如果我想在函数中提取代码段,我应该在$scope $scope.myfunc = function()下创建函数,还是像var myfunc = function那样直接创建?

1 个答案:

答案 0 :(得分:0)

我像这样重构了它..

var dcApp = angular.module("dcApp", ["dcApp.services"])


dcApp.controller("filterController",["$scope", "filterService",
    function ($scope, filterService) {
        var filterSentData = {
            specie: "all",
            cellinfo: "all",
            factor: "all",
            hideincomplete: "show",
            keyword: "",
            clicked: null,
            page: 1
        }

        var filterAjaxUpdate = function(sent) {
            filterService.setFilterSentData(sent)
            filterService.request().success(function (reply, status) {
                $scope.species = reply.species
                $scope.cellinfos = reply.cellinfos
                $scope.factors = reply.factors
                $scope.datasets = reply.datasets
            })
        }

        filterAjaxUpdate(filterSentData)

        $scope.setFilter = function(key, content) {
            filterSentData[key] = content
            filterAjaxUpdate(filterSentData)

        }


    }]);