【问题标题】:AngularJS: accessing scope in $resource factory definitionAngularJS:访问 $resource 工厂定义中的范围
【发布时间】:2013-04-24 20:49:50
【问题描述】:

我正在运行一个包含 Pusher 的 AngularJS 应用程序,用于实时更新模型。当推送器为工厂定义中的 AngularJS 资源发送更新数据时,我想在范围内触发一个动作。

我有一个资源定义如下:

TS.app.factory "Object", ($resource) ->
  Object = $resource("objects/:publicToken", {publicToken: "@public_token"}, {update: {method: "PUT"}})

  # Checks for updates to object data via Pusher.
  Object::watch = ->
    channelName = "private-12345"

    # See if we've already subscribed to this channel.
    channel = Namespace.pusher.channel(channelName)

    # If not, subscribe.
    channel ||= Namespace.pusher.subscribe(channelName)

    # Update data if we get new info from pusher.
    channel.bind "updated info", (data) =>
      # THIS GETS RUN WHEN PUSHER SENDS UPDATED DATA.
      for key, value of data
        this[key] = value
      # TRIGGER ACTION HERE

我想在此资源的范围内设置变量。我知道对于像 $get 这样的方法,范围会自动更新,但我不知道在这种情况下如何做到这一点。如何访问此处的范围?

如果有其他更好(或更多 Angular-y)的方法来做到这一点,它们是什么?

【问题讨论】:

    标签: angularjs coffeescript pusher


    【解决方案1】:

    您绝对不希望您的服务知道您的模型或直接访问它们。听起来您想在服务上使用观察者模式,并让任何关心获取通知的控制器订阅您的服务。

    这是一个简单的例子:http://jsfiddle.net/langdonx/sqCZz/

    HTML

    <div ng-app="app" ng-controller="testController">
        <div ng-repeat="notification in notifications">{{notification}}</div>
    </div>
    

    JavaScript

    angular.module('app', [])
        .factory('TestService', function () {
        var _subscribers = [];
    
        setInterval(function () {
            // every 1 second, notify all subscribers
            console.log(_subscribers);
            angular.forEach(_subscribers, function (cb) {
                cb('something special @ ' + new Date());
            });
        }, 2500);
    
        return {
            subscribe: function (cb) {
                _subscribers.push(cb);
            }
        };
    })
        .controller('testController', function ($scope, TestService) {
        $scope.notifications = ['nothing yet'];
    
        TestService.subscribe(function (notification) {
            $scope.$apply(function () {
                $scope.notifications.push('got ' + notification);
            });
        });
    });
    

    【讨论】:

    • 在您的第一句话中,您是指控制器而不是模型吗?
    • 我认为如果我只有一个对象,这将是一个合理的解决方案,但我实际上有大约 100-200 个。将进行测试,但我猜这会降低性能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2016-08-02
    • 2012-11-05
    • 2015-03-04
    • 1970-01-01
    相关资源
    最近更新 更多