2016-03-05 63 views
0

我正在创建一个多人游戏,并且我希望在第一个玩家更新集合中的“isStarted”字段后执行特定的功能。在角质流星收集更新后执行一个功能

在我的控制,我有:

angular.module('mcitygame').directive('gcaseGame', function() { 
return { 
    restrict: 'E', 
    templateUrl: 'client/gcases/gcase-game/gcase-game.html', 
    controllerAs: 'gcaseGame', 
    controller: function($scope, $stateParams, $reactive, $window, $element) { 

     $reactive(this).attach($scope); 

     this.subscribe('gcases'); // This is the collection I need to watch if the "isStarted" field has changed 

     this.helpers({ 
      gcase:() => { 
       return GCases.findOne({_id: 'dynamicID'}) //I'm using $stateParams.gcaseId, which I get from the router, but I put 'dynamicID' just for the purpose of this example. 
      }); 

     this.startGame = function(option){ 
      if(option == 1) { 
       console.log(" Users clicked me from the interface!"); 
       GCases.update({_id :'dynamicID'}, { 
        $set: {isStarted: true, updatedAt: Date.now()} 
       }); 
      } else { 
       console.log("I am here because someone called me from a different client!"); 
      } 

     }; 

     ////////////////////////// I need to be able to do something like this 
     this.autorun(() => { 
      if(this.gcase.isStarted){ 
       console.log(" isStartred = " + this.gcase.isStarted); 
       this.startGame(); 
      } 
     }); 
     ////////////////////////// or this 
     this.gcase.observeChanges({ 
      changed: function (id, gcase) { 
       console.log(" isStartred = " + this.gcase.isStarted); 
       this.startGame(); 
      } 
     }); 
     ////////////////////////// 

    } 
}}) 

控制器之外,我有:

GCases = new Mongo.Collection("gcases"); 

任何帮助将非常感激..

回答

0

好了..就我所做的是这样的:

var that = this; // I did this since I need to call it from inside 'observeChanges' 
    GCases.find({_id:'dynamicID'}).observeChanges({ //'this.gcase', as proposed in the question, was returning an error saying it's not a function 
     changed: function (id, gcase) { 
      console.log(" isStartred = " + gcase.isStarted); 
      that.startGame(2); // any value beside 1 will invoke the 'else' condition, and the log will only appears on other clients consoles 
     } 
    }); 

和它的工作。我不确定是否有更好的方法,但这是一条路。希望你觉得这有帮助。

0

您可以使用一个回调函数在更新中。

+0

如果更新是由其他客户端进行的,那么这不会对他有所帮助。 –