LoginSignup
1
1

More than 3 years have passed since last update.

CreateJSでの継承

Posted at

いつも書くたびに継承の書き方を忘れてしまうので備忘録。

CreateJSの継承(prototype)

私は基本prototypeでの継承しか使わないので、こちらをメモ。


var ViewContainer = function(name){
  this.Container_constructor();

  // 好きな初期化処理を書く
  this.name = name;
}
// これをいつも忘れてしまいがち
createjs.extend(ViewContainer, createjs.Container);
createjs.promote(ViewContainer, 'Container');

ViewContainer.prototype.setBGColor = function(color){
  // hogehoge......
}

いつも

createjs.extend(ViewContainer, createjs.Container);
createjs.promote(ViewContainer, 'Container');

の記法を忘れてしまいます。
ここは継承したいCreateJSのクラスと、継承する自作のクラスに好きに差し替えてください

CreateJSの継承使いどころ

CreateJSでUIとかを描画するときにはView・Buttonなどのオブジェクトを毎回作るのは面倒なので、Containerを継承させてクラスを作成しておくと便利です。
よく私が作っているクラスをサンプルで置いておきます。

ViewContainer.js
/**
 * @classdesc View生成用のContainer
 * @param {string} name 
 */
var ViewContainer = function(name,width,height)
{
  this.Container_constructor();
  this.name = "view_container";
  this._name = name;
  this._width = width;
  this._height = height;
}
createjs.extend(ViewContainer, createjs.Container);
createjs.promote(ViewContainer, 'Container');

/**
 * @param {string} color - 背景用のカラーコード #000000 ~ #FFFFFF
 */
ViewContainer.prototype.setBGColor = function(color)
{
  if(this.bg_shape != undefined) container.removeChild(this.bg_shape);
  var graphics = new createjs.Graphics();
  graphics.beginFill(color);
  graphics.rect(0,0,this._width,this._height);

  this.bg_shape =  new createjs.Shape(graphics);
  this.addChild(this.bg_shape);
}
ButtonContainer.js

/**
 * @classdesc Button生成用のContainer
 * @constructor
 */
var ButtonContainer = function()
{
  this.Container_constructor();
}
createjs.extend(ButtonContainer, createjs.Container);
createjs.promote(ButtonContainer, 'Container');

/**
 * @param {number} width 
 * @param {number} height 
 */
ButtonContainer.prototype.setSize = function(width,height)
{
  this._width = width;
  this._height = height;
}
/**
 * @param {string} color - 背景用のカラーコード #000000 ~ #FFFFFF
 */
ButtonContainer.prototype.setBGColor = function(color)
{
  if(this.bg_shape != undefined) this.removeChild(this.bg_shape);
  var graphics = new createjs.Graphics();
  graphics.beginFill(color);
  graphics.rect(0,0,this._width,this._height);

  this.bg_shape =  new createjs.Shape(graphics);
  this.addChild(this.bg_shape);
}

/**
 * @param {callback} callback
 */
ButtonContainer.prototype.onClick = function(callback)
{
  this.removeAllEventListeners('click');
  this.addEventListener('click', callback);
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1