r3-legacy/src/game-lib-custom-code.js

139 lines
3.1 KiB
JavaScript

/**
* Creates a CustomCode object
* @param apiCustomCode GameLib.API.CustomCode
* @constructor
*/
GameLib.CustomCode = function(
apiCustomCode
) {
if (GameLib.Utils.UndefinedOrNull(apiCustomCode)) {
apiCustomCode = {};
}
if (apiCustomCode instanceof GameLib.CustomCode) {
return apiCustomCode;
}
GameLib.API.CustomCode.call(
this,
apiCustomCode.id,
apiCustomCode.name,
apiCustomCode.eventId,
apiCustomCode.code,
apiCustomCode.parentEntity
);
this.editor = null;
GameLib.Component.call(this);
};
GameLib.CustomCode.prototype = Object.create(GameLib.API.CustomCode.prototype);
GameLib.CustomCode.prototype.constructor = GameLib.CustomCode;
GameLib.CustomCode.prototype.createInstance = function() {
try {
this.instance = new Function('data', this.code).bind(this);
} catch (error) {
/**
* Set the instance to true here to indicate that even though the compilation failed, the instance will be fine and
* this component loaded fine.
*/
this.instance = new Function('data', "console.log('compilation failed for : " + this.name + "');").bind(this);
}
GameLib.Component.prototype.createInstance.call(this);
};
/**
* Updates the instance with the current state
*/
GameLib.CustomCode.prototype.updateInstance = function() {
try {
this.instance = new Function('data', this.code).bind(this);
this.publish(
GameLib.Event.COMPILE_SUCCESS,
{
component : this
}
)
} catch (error) {
this.instance = new Function('data', "console.log('compilation update failed for : " + this.name + "');").bind(this);
this.publish(
GameLib.Event.COMPILE_FAILED,
{
component : this
}
)
}
};
/**
* Converts a GameLib.CustomCode to a new GameLib.API.CustomCode
* @returns {GameLib.API.CustomCode}
*/
GameLib.CustomCode.prototype.toApiObject = function() {
return new GameLib.API.CustomCode(
this.id,
this.name,
this.eventId,
this.code,
GameLib.Utils.IdOrNull(this.parentEntity)
);
};
/**
* Converts from an Object CustomCode to a GameLib.CustomCode
* @param objectCustomCode Object
* @returns {GameLib.CustomCode}
* @constructor
*/
GameLib.CustomCode.FromObject = function(objectCustomCode) {
var apiCustomCode = GameLib.API.CustomCode.FromObject(objectCustomCode);
return new GameLib.CustomCode(
apiCustomCode
);
};
GameLib.CustomCode.prototype.launchEditor = function(){
GameLib.Event.Emit(
GameLib.Event.GET_RUNTIME,
null,
function(runtime) {
this.coder = runtime.coder;
this.coder.isNotCodeMirrorThrow();
}.bind(this)
);
this.editor = this.coder.instance(
document.body,
{
value : this.code,
mode : 'javascript',
lineNumbers : true,
scrollbarStyle : 'overlay',
indentWithTabs: true,
indentUnit : 4
}
);
this.editor.on('change', function(){
this.code = this.editor.getValue();
this.updateInstance();
}.bind(this))
};
GameLib.CustomCode.prototype.closeEditor = function(){
var dom = this.editor.getWrapperElement();
dom.parentElement.removeChild(dom);
};