Javascript
Template:Otherlang2 Panorama использует Javascript в качестве скриптового языка, позволяя пользовательскому интерфейсу динамически реагировать на действия пользователя и события игры. Код Javascript выполняемый в клиенте может взаимодействовать с кодом сервера пользовательской игры (реализованном в Lua.)
Javascript API
Panorama JS API в основном расширенный вариант Scaleform ActionScript API.
Задокументировано: Dota 2 Workshop_Tools/Panorama/Javascript/API
Рабочий процесс
Подключаем Scripts
Ваш Panorama XML может ссылаться на JS файлы в блоке 'scripts'
, или включать в себя Javascript в блоке 'script'
(подходит только для не очень большого кода.)
<root>
<scripts>
<!--
Это ссылка на script файл расположенного в:
content/dota_addons/ADDON_NAME/scripts/custom_game/my_script_name.js
-->
<include src="file://{resources}/scripts/custom_game/my_script_name.js" />
</scripts>
<script>
// Это встроенный Javascript в код (XML experts: Panorama automatically wraps your script block inside a CDATA section.)
$.Msg( "Hello, world!" );
</script>
<Panel>
<!-- (Иерархия Panel находится здесь.) -->
</Panel>
</root>
(Данный script автоматически скомпилирован по адресу: game/dota_addons/ADDON_NAME/scripts/custom_game/my_script_name.vjs_c
или может быть скомпилирован вручную с помощью resourcecompiler.)
Процесс перезагрузки
Когда panel перезагружается, связанный с ним javascript выполнится повторно. Это обычно приводит к заданному поведению, но иногда приводит к путанице. When iterating on a complicated UI, it's usually worth the trouble to ensure that your script is robust to being reloaded. Callbacks registered with the system for things like game events will automatically be ignored when they go stale - it's safe to re-register. However, if you're dynamically creating panels, consider checking to see if they're already there for a previous reload. A bit of careful checking can go a long way to improving your iteration speed.
Panels
Creating Panels
A powerful way to reuse parts of your UI is to dynamically create panels. For example, the multiteam scoreboard creates a new child panel for each team, and in turn each team panel creates a new child panel for each player. This way the UI can dynamically adapt to any number of teams and players, with a single copy of XML/CSS/JS for each concept.
var parentPanel = $.GetContextPanel(); // the root panel of the current XML context
var newChildPanel = $.CreatePanel( "Panel", parentPanel, "ChildPanelID" );
newChildPanel.BLoadLayout( "file://{resources}/layout/custom_game/new_panel.xml", false, false );
Accessing CSS Properties From Javascript
Many CSS properties can be accessed from javascript via MyPanel.style.property
. Due to syntax differences between the two languages their names are not identical to their CSS equivalent (this is the same on the web) but are easily deducible: Hyphen-delimited words are converted to camelCase equivalent. For example background-color
in CSS is style.backgroundColor
in Javascript.
$ (Dollar Sign)
Several important global routines are accessible through the $
global object
JQuery-Like Selection
As with JQuery, you can find a panel in the current context using $( "#PanelID" )
. Note that this currently has significant limitations: it can only match a single panel by ID. If there is no matching panel it will return null instead of a empty selector, which can result in unexpected JS errors. (And failure of the rest of the script to execute.)
$( "#MyLabel" ).text = "hello";
Msg
For simple logging, use $.Msg()
- it supports all Javascript types and any number of arguments. (It will print all the arguments consecutively on a single line.)
// This will print: Hello {"who":"world"}!
$.Msg( "Hello ", { "who": "world" }, "!" );
GetContextPanel
$.GetContextPanel()
returns the root "context panel" that the script is running for. (Very similar to 'this' or 'self' in other languages.) This is the root panel of the XML that loaded the script.
<root>
<script>
$.GetContextPanel().SetHasClass( "context_panel", true ); // after this it will have both "context_panel" and "root_panel" classes
</script>
<Panel class="root_panel">
<Label text="Hi" />
</Panel>
</root>
Game APIs
Game Events
Javascript can register functions to get called when game events are fired. This works for both engine events and new Custom Game Events:
function OnFoo( data ) { $.Msg( "foo_event: ", data ); }
var handle = GameEvents.Subscribe( "foo_event_name", OnFoo );
GameEvents.Unsubscribe( handle );
Custom Nettables
Custom nettables are a way to communicate persistent state from the server to clients. See: Dota 2 Workshop Tools/Custom Nettables
Best Practices and Javascript Gotchas
"use strict"
Our example Javascript code employs the ["use strict"] feature to increase safety, robustness, and sanity.
That Weird Anonymous Function Thing (IIFE)
In our example Javascript, you may see use of the [Immediately-invoked Function Expression (IIFE)] pattern.
(function () {
$.Msg( "The panel associated with this javascript just got loaded or reloaded!" );
})();
Triple Equals
If you're familiar with C-family languages, you may be surprised to learn that Javascript has two equality operators: '==' and '==='
You can learn more about this [here] or elsewhere on the web.
Variable Capture
If you're coming to Javascript from another language, you should know that nested functions capture their enclosing scope by reference, which can lead to unexpected results:
var closures_bad = [];
var closures_good = [];
function create()
{
for (var i = 0; i < 5; i++)
{
closures_bad[i] = function()
{
$.Msg( "i = ", i );
};
closures_good[i] = (function( j ){return function()
{
$.Msg( "i = ", j );
}}(i));
}
}
function run()
{
// prints "5 5 5 5 5" because loop variable 'i' is captured by reference above
for (var k = 0; k < 5; k++)
{
closures_bad[k]();
}
// prints "0 1 2 3 4" because each value of loop 'i' is captured by a different function parameter 'j'
for (var k = 0; k < 5; k++)
{
closures_good[k]();
}
}
create();
run();
Misc
Panorama Javascript execution is handled by the Google V8 javascript engine.