本章講解腳本移除命令RemoveScriptCommand.js,這個文件的主要功能就是移除腳本execute、還原腳本undo。
//刪除腳本命令
var RemoveScriptCommand = function ( object, script ) {
//繼承自Command,只是調用一下Command方法,將this傳遞過去
Command.call( this );
//命令類型
this.type = 'RemoveScriptCommand';
//命令名稱
this.name = 'Remove Script';
//操作的對象
this.object = object;
//需要移除的腳本(保存當前腳本,撤銷時需要恢復腳本)
this.script = script;
//對象腳本都存在時,找到腳本的索引
if ( this.object && this.script ) {
this.index = this.editor.scripts[ this.object.uuid ].indexOf( this.script );
}
};
RemoveScriptCommand.prototype = {
//執行命令
execute: function () {
//查找對象的腳本
if ( this.editor.scripts[ this.object.uuid ] === undefined ) return;
//腳本的索引存在
if ( this.index !== - 1 ) {
//移除腳本
this.editor.scripts[ this.object.uuid ].splice( this.index, 1 );
}
this.editor.signals.scriptRemoved.dispatch( this.script );
},
//撤銷命令
undo: function () {
//腳本不存在
if ( this.editor.scripts[ this.object.uuid ] === undefined ) {
//建立腳本列表
this.editor.scripts[ this.object.uuid ] = [];
}
//將原來的腳本放入到腳本列表
this.editor.scripts[ this.object.uuid ].splice( this.index, 0, this.script );
//更新腳本ui
this.editor.signals.scriptAdded.dispatch( this.script );
},
//序列化
toJSON: function () {
var output = Command.prototype.toJSON.call( this );
output.objectUuid = this.object.uuid;
output.script = this.script;
output.index = this.index;
return output;
},
//反序列化
fromJSON: function ( json ) {
Command.prototype.fromJSON.call( this, json );
this.script = json.script;
this.index = json.index;
this.object = this.editor.objectByUuid( json.objectUuid );
}
};