Source: view/ViewRectangleSprite.js

/**
 * @author    Wolfgang Kowarschick <kowa@hs-augsburg.de>
 * @copyright 2017 - 2018
 * @license   CC-BY-NC-SA-4.0
 */

import {Sprite} from 'pixi.js';

/**
 * @class
 */
class ViewRectangleSprite
{ /**
   * @param {Object}         p_pixi_app
   * @param {ModelRectangle} p_model
   * @param {Object}         p_config
   * @param {string}         [p_config.image = null]
   * @param {Object}         p_resources
   */
  constructor(p_pixi_app, p_model, { image: p_image }, p_resources)
  { this.v_resources = p_resources;
    
    /**
     * The model to be visualized.
     * @member {ModelRectangle} ViewRectangleSprite#model
     */
    this.model = p_model;
    
    /**
     * The sprite object that visualizes the model.
     * @member {PIXI.Sprite} ViewRectangleSprite#sprite
     */
    this.sprite = new Sprite();
    
    p_pixi_app.stage.addChild(this.sprite);
    
    if (p_image != null)
    { this.image = p_image;
      this.render();
    }
  }
  
  /**
   * The resource name of the image to be used as texture of the rectangle.
   * @member {string} ViewRectangleSprite#image
   */
  set image(p_image)
  { const c_sprite = this.sprite;
  
    c_sprite.texture = this.v_resources[p_image].texture;
    
    if (this.model.width)
    { c_sprite.width = this.model.width; }
    if (this.model.height)
    { c_sprite.height = this.model.height; }
  }
  
  /**
   * Adds a listener to PixiJS events dispatched by <code>this.sprite</code>.
   * @see http://pixijs.download/dev/docs/PIXI.Sprite.html
   *
   * @param {string}   p_event    - the name of the PixiJS event to be listened to
   * @param {Function} f_listener - the listener
   */
  addEventListener(p_event, f_listener)
  { this.sprite.interactive = true;
    this.sprite.on(p_event, f_listener);
  }
  
  /**
   * Renders the view.
   */
  render()
  { this.sprite.x = this.model.x;
    this.sprite.y = this.model.y;
  }
}

export {ViewRectangleSprite};