我正在创建一个多人游戏,我希望在第一个玩家更新集合中的“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 :(得分:0)
您可以在更新中使用回调函数。
答案 1 :(得分: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
}
});
它有效。我不确定是否有更好的方法,但这是一种方法。希望你觉得这很有帮助。