我正在开发一款游戏,它使用angular.js作为ui和游戏引擎类。
由于游戏引擎类和角度素材库之间存在冲突,我必须在角度后按顺序加载游戏引擎。
一旦游戏引擎被初始化,它会发送一个自定义的dom事件“clientReady”,附加了2个对象,我需要在我的角度控制器中访问。
所以在app.run上我将这2个对象初始化为根范围,如下所示:
app.run(function($rootScope) {
$rootScope.engine = {};
$rootScope.editor = {};
document.addEventListener('clientReady', function(e) {
$rootScope.$apply(function() {
$rootScope.engine = e.detail.engine;
$rootScope.editor = e.detail.editor;
});
});
});
现在在我的控制器中我试图设置范围如:
$scope.player = $rootScope.engine.player;
这当然不起作用,因为“clientReady”事件在角度初始化后发生,并且在开始运行控制器时rootcope不存在。
有办法解决这个问题吗?我想知道我是否可以在dom事件之后以某种方式启动控制器。
此致 斯蒂芬
答案 0 :(得分:1)
您无法“启动”控制器。您可以转到视图,它将运行控制器并将控制器的范围与其对应的视图绑定。
因此,如果您希望始终收听此事件,则应在BodyController中执行此操作。但是,如果您只想在某些视图上收听此事件,那么您应该只在app.run
上执行此操作
app.controller('BodyController', function($rootScope) {
$document.addEventListener('clientReady', function(e) {
// Decide based on view when you want to change initialize the game or not
if($location.path == '/login') {
// don't let the user init as he/she is not logged in
} else {
//init
// Store e in a service or $rootScope. I'd pick a service to do this as I wouldn't want to clutter my $rootScope
GameService.save(e);
// Handle transition to the new path
$location.path('/something');
}
});
})
或者如果你只想在一个或多个视图上听这个。 1.在一个或多个视图上监听clientReady事件(假设此事件仅初始化一次)
所以,让我们说你的家/默认视图是'/'。然后在HomeController中,你这样做:
app.controller('MainCtrl', function($scope, $document) {
$document.addEventListener('clientReady', function(e) {
// Store e in a service or $rootScope. I'd pick a service to do this as I wouldn't want to clutter my $rootScope
GameService.save(e);
// Goto to View/Controller that needs e
$location.path('/something');
});
}
isInitialized()
仅在clientReady
事件被触发时才返回true。如果isInitialized()return false, then the $location will be changed and execution of GameCtrl will stop (because of
return`陈述)
app.controller('GameCtrl', function($scope, GameService, $location) {
if(!GameService.isInitialized()) {
$location.path('/home'); // or to any other route you deem fit
// Instead of redirecting, you can handle this gracefully on this view too. But I think that'll take much more effort.
return; //Important so that the controller is not processed any further
}
// This is where the magic happens!
$scope.engine = GameService.getEngine();
$scope.editor = GameService.getEditor();
}
GameService
是存储游戏引擎和其他客户端给定对象的地方。
angular.module('myApp').service('GameService', function() {
// AngularJS will instantiate a singleton by calling "new" on this function
this.getEngine = function() {
// Logic
}
this.getEditor = function () {
// Logic
}
this.isInitialized = function () {
// Logic
}
};
答案 1 :(得分:0)
您可以使用$broadcast & $on
进行通信。
document.addEventListener('clientReady', function(e) {
var objData = {};
objData.engine = e.detail.engine;
objData.editor = e.detail.editor;
$rootScope.$broadcast('updated-data',{objData : objData});
});
在控制器中,
$scope.$on('updated-data',function(event,eveneData){
console.log(eveneData);
})