【问题标题】:AngularJS PouchDB change-listenerAngularJS PouchDB 更改监听器
【发布时间】:2016-03-30 19:06:49
【问题描述】:

我在网络上关注了一些关于待办事项列表的教程......但我认为,这些教程没有使用最佳实践来实现。所有代码都在控制器中。 我的控制器看起来像这样,我认为更改侦听器的代码不是在那里的最佳“位置”。我应该在哪里实现监听器?

.controller('TodosCtrl', ['$scope', '$state', 'Todo', function($scope, $state, Todo) {
  $scope.create = function() { $state.go('todo_create'); };
  $scope.todos= [];
  $scope.$on('$ionicView.loaded', function() {
    localDB.changes({ 
      since: 'now',
      live: true,
      include_docs: true
    }).on('change', function (change) {
      if (change.doc && change.doc._id.substring(0, change.doc._id.indexOf('_')) === 'todo') {
        if (change.deleted) {
            ....
        } else {
            ....
        }
      }
    });
  });


  Todo.all().then(function (result) { 
    for (var i = 0; i < result.length; i++) {
      $scope.todos.push(result[i].doc);
    }
  });


}]) 

【问题讨论】:

    标签: javascript angularjs ionic-framework pouchdb


    【解决方案1】:

    从概念上讲,与 DOM 耦合的所有相关代码都应该在控制器中。
    所有其他逻辑都应该插入到服务中。

    查看我的评论以获取示例:

    .controller('TodosCtrl', ['$scope', '$state', 'Todo', function($scope, $state, Todo) {
            $scope.create = function() { $state.go('todo_create'); };
            $scope.todos= [];
            $scope.$on('$ionicView.loaded', function() {
                localDB
                    /** Not sure exactly what it is but if that some sort of initialization - this is better to be placed in one of the services 
                    .changes
                    ({
                        since: 'now',
                        live: true,
                        include_docs: true
                    })
                    */
                    .on('change', function (change) {
                        if (change.doc && change.doc._id.substring(0, change.doc._id.indexOf('_')) === 'todo') {
                            if (change.deleted) {
                            ....
                            } else {
                            ....
                            }
                        }
                    });
            });
    
    
            Todo.all().then(function (result) {
                for (var i = 0; i < result.length; i++) {
                    $scope.todos.push(result[i].doc);
                }
            });
        }]) ;
    

    【讨论】:

    • 但是我在监听器中使用了$scope变量……所以代码和dom有关,对吗?
    • 如果需要 $scope,我如何将监听器放入服务中?
    • $scope 是特定于每个控制器的,不能在服务内部关联。这意味着您确实不能将侦听器放入服务中。您可以在侦听器中放置的就是我在代码中提到的初始化(以及其他非 DOM 依赖的东西)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2010-09-08
    • 2011-07-16
    相关资源
    最近更新 更多