在 AngularJS 代码中使用此扩展的正确方法是什么

What's the proper way to use this extension in AngularJS code?

本文关键字:方法 是什么 扩展 代码 AngularJS      更新时间:2023-09-26

我正在使用一个名为Radiant UI的框架,这是一种将HTML5 UI引入虚幻引擎4的方法。我正在尝试在这样做的同时学习一些现代Javascript,所以我正在用AngularJS构建UI。

不过,我对 Angular 的理解仍然很薄弱,我对这里的最佳实践有点困惑。该扩展在设置时注入以下 Javascript。

var RadiantUI;
if (!RadiantUI)
  RadiantUI = {};
(function() {
  RadiantUI.TriggerEvent = function() {
    native function TriggerEvent();
    return TriggerEvent(Array.prototype.slice.call(arguments));
  };
  RadiantUI.SetCallback = function(name, callback) {
    native function SetHook();
    return SetHook(name, callback);
  };
  RadiantUI.RemoveCallback = function(name) {
    native function RemoveHook();
    return RemoveHook(name);
  };
})();;

因此,这只是将RadiantUI推送到全局命名空间中。如果扩展名始终存在,那就好了,但事实并非如此。在测试环境(Chrome)中,它不存在。它仅在游戏引擎中运行时存在。这一点,再加上全局变量很糟糕的事实,意味着我想封装它。

之前的迭代中,我将其包装在AMD模块中,并且运行良好。喜欢这个:

define([], function()
{
    if ("RadiantUI" in window)
    {
        console.log("RadiantUI in global scope already!");
        return window.RadiantUI;
    }
    var RadiantUI;
    if (!RadiantUI) {
        RadiantUI = {};
        RadiantUI.TriggerEvent = function() {}
        RadiantUI.SetCallback = function() {}
        RadiantUI.RemoveCallback = function() {}
    }
    console.log("Using fake RadiantUI bindings");
    return RadiantUI;
});

所以这就是我想做的:

我想将 Radiant 作为我的应用程序/状态提供商的依赖项包含在内,并将其注入,就像在 AMD 中一样。如果扩展不存在,则使用存根方法。正确的方法是什么?模块?服务提供商?

更新:这是使用给定答案的工作代码。

var myapp = angular.module('bsgcProtoApp', ['ui.router' ]);
myapp.value('radiant', window.RadiantUI || {
    TriggerEvent: function()
    {
        console.log("TriggerEvent called");
    },
    SetCallback: function(name, callback)
    {
        console.log("Setcallback called");
    },
    RemoveCallback: function(name)
    {
        console.log("RemoveCallback called");
    }
});
myapp.config(['$stateProvider', '$urlRouterProvider',  function($stateProvider, $urlRouterProvider )
{
    $urlRouterProvider.otherwise("/mainmenu");
    $stateProvider.state('mainmenu',
    {
        name: "mainmenu",
        url: "/mainmenu",
        templateUrl: 'templates/mainmenu.html',
        controller: ['$scope', 'radiant', function($scope, radiant)
        {
            $scope.tester = function()
            {
                radiant.TriggerEvent("DuderDude");
                console.log("Duder!");
            }               
        }],
    });
}]);

你可能有一个Angular模块或应用程序。为了这个答案,我们称之为MyApp.

现在你可以做

MyApp.value("RadiantUI", window.RadiantUI || {
    TriggerEvent = function(){},
    //... more properties
});

现在,例如,要将此值作为控制器中的依赖项进行访问,您将这样做

MyApp.controller(["$scope", "RadiantUI", function($scope, RadiantUI){
    // ... controller code ...
}]);