本節講解腳本命令中的添加腳本AddScriptCommand.js,每個命令都會有2個函數execute、undo,其中execute函數是用來處理命令的執行過程(添加、重新執行該命令),undo用來處理撤銷命令。命令的結構簡單易用、易擴展,符合開放封閉原則。
添加腳本命令的主要功能是完成腳本添加、腳本編輯撤銷功能。
//添加腳本命令
var AddScriptCommand = function ( object, script ) {
//設置其他屬性
Command.call( this );
//命令類型
this.type = 'AddScriptCommand';
//命令名稱
this.name = 'Add Script';
//對象、新腳本
this.object = object;
this.script = script;
};
AddScriptCommand.prototype = {
//執行命令
execute: function () {
//查找對象的腳本列表
if ( this.editor.scripts[ this.object.uuid ] === undefined ) {
//腳本不存在就創建
this.editor.scripts[ this.object.uuid ] = [];
}
//添加新腳本
this.editor.scripts[ this.object.uuid ].push( this.script );
//腳本添加後派發消息
this.editor.signals.scriptAdded.dispatch( this.script );
},
//撤銷命令
undo: function () {
//腳本不存在就返回
if ( this.editor.scripts[ this.object.uuid ] === undefined ) return;
//查找腳本的索引
var index = this.editor.scripts[ this.object.uuid ].indexOf( this.script );
//找到腳本就刪除
if ( index !== - 1 ) {
this.editor.scripts[ this.object.uuid ].splice( index, 1 );
}
//移除腳本,派發消息
this.editor.signals.scriptRemoved.dispatch( this.script );
},
//序列化
toJSON: function () {
var output = Command.prototype.toJSON.call( this );
output.objectUuid = this.object.uuid;
output.script = this.script;
return output;
},
// 反序列化
fromJSON: function ( json ) {
Command.prototype.fromJSON.call( this, json );
this.script = json.script;
this.object = this.editor.objectByUuid( json.objectUuid );
}
};