Tips for expanding the capabilities of the PixiJS v7 Container class

I am in the process of migrating a word game from Pixi.js version 6.5.9 to 7.2.3:

https://i.sstatic.net/aurP5.png

Within the game, I utilize a custom class called Tile.js to depict the yellow draggable letter tiles:

'use strict';

function Tile(letter, value) {
    PIXI.Container.call(this); 

    this.col = NaN;
    this.row = NaN;
    this.letter = letter;
    this.value = value;
    
    this.drag = false;

    this.graph = new PIXI.Graphics();
    this.addChild(this.graph);

    this.letterText = new PIXI.Text('', {fontFamily: 'Arial', fontSize: 40, fill: 0x000000});
    this.letterText.anchor.set(0.5);
    this.addChild(this.letterText);

    this.indexText = new PIXI.Text('', {fontFamily: 'Arial', fontSize: 20, fill: 0x000000});
    this.indexText.anchor.set(1);
    this.addChild(this.indexText);

    this.setLetter(letter);
    this.setValue(value);
}

This class extends the PIXI.Container class using the following code snippet:

Tile.prototype = Object.create(PIXI.Container.prototype);
Tile.prototype.constructor = Tile;

Additionally, to enable dragging functionality, I have incorporated the following methods:

Tile.prototype.setIteractive = function(onDragStart, onDragMove, onDragEnd) {
    this.eventMode = 'static'; 
    this.buttonMode = true;

    this.hitArea = new PIXI.Rectangle(0, 0, Tile.WIDTH, Tile.HEIGHT);

    this.on('pointerdown', onDragStart)
        .on('pointermove', onDragMove)
        .on('pointerup', onDragEnd);
 };

Tile.prototype.startDragging = function() {
    this.drag = true;
    this.scale.x = 1.4;
    this.scale.y = 1.4;
    this.alpha = 0.9;
};

Tile.prototype.stopDragging = function() {
    this.drag = false;
    this.scale.x = 1;
    this.scale.y = 1;
    this.alpha = 1;
};

Upon upgrading from Pixi.js version 6.5.9 to 7.2.3, an error is encountered in the Edge browser console:

Uncaught TypeError: Class constructor _Container cannot be invoked without 'new'

https://i.sstatic.net/ROduR.png

Has the method I used for extending the Container class been deprecated?

I have delved into the source code available at Github in an attempt to grasp the correct approach for extending classes in PixiJS v7... I have tried to comprehend how Container inherits from DisplayObject, but the syntax seems quite different (potentially due to it being written in TypeScript?)...

UPDATE:

Pursuing the suggestion by @domis86, I have refactored my custom Tile.js class to incorporate a PIXI.Container member:

function Tile(letter, value) {
    var _col = NaN;
    var _row = NaN;
    var _letter = letter;
    var _value = value;
    
    var _drag = false;
    
    var _cont = new PIXI.Container();
    _cont.eventMode = 'static';
    _cont.buttonMode = true;
   
    _graph
    
    ...and more functions...

    // return the public methods
    return {
        getContainer: getContainer,
        setIteractive: setIteractive,
        startDragging: startDragging,
        stopDragging: stopDragging,
        ...
        redraw: redraw
    };
}

Answer №1

Check out my jsfiddle creation:

https://jsfiddle.net/k1qr5m8g/

(This is a modified example inspired by user bigtimebuddy from the question "what's the best way to implement dragging in version 7?" - https://github.com/pixijs/pixijs/discussions/8813#discussioncomment-4038065)

Take a look at it and see the browser console for interesting outputs after clicking on the rectangle (sprite):

The Tile.getMyValue() function was called - value: 123
Dumping "this":
Object { iAmTile: true }

The PixiJS Elementals tutorial mentions a method to pass a custom object (in this case, the Tile instance) to mouse events:

Pay attention to this code snippet:

// By passing "that" (the original "this" of the Tile object instance) as the third argument,
// The "this" inside getMyValue function will refer to the Tile instance.
sprite.on('pointerdown', getMyValue, that);

Additionally, I suggest converting your code to an ES6 class structure, as demonstrated in

Furthermore, do you create instances of Tile objects using the "new" keyword in your code? Look at the end of the jsfiddle for reference:

var tileInstance = new Tile('A', 123, app);
tileInstance.initializeInteractiveListeners();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to incorporate HTML code blocks like headers and footers on all pages using the ejs templating engine in Node.js?

Is it possible to achieve a similar result as in PHP? For instance, if I have a header.ejs file which includes the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Tit ...

Can dynamic loading JavaScript be debugged using a debugger such as WebKit, FireBug, or the Developer Tool in IE8?

After asking a question on Stack Overflow, I have successfully written JavaScript functions for loading partial views dynamically. However, debugging this dynamic loading script has been a challenge for me due to all loaded JavaScript being evaluated by th ...

What is the right way to import a module in TypeScript?

There is a module that I have declared like so: declare module conflicts { export interface Item {} export interface Item2 {} export interface Item3 {} } I attempted to import this module in a component using the following code: import * from ...

How can you utilize an injected service from inside a Class decorator in Typescript/NestJS?

Can an injected service be accessed from within a Class decorator? I aim to retrieve the service in the personalized constructor: function CustDec(constructor: Function) { var original = constructor; var f: any = function (...args) { // How can I ...

What is the method for accessing a local XML file with $.ajax?

Currently, I am working on developing a Firefox extension that requires reading a local XML file. However, I have encountered an issue with using $.ajax to read the file. Here is a snippet of my code: $.ajax({ type: "GET", url: "file:/// ...

Various successful functions in Ajax

I am currently using an Ajax script to fetch data from my database and insert it into multiple textboxes. Along with posting the data, I also need to perform calculations using these textboxes. However, upon running the script, I noticed that all calculat ...

Creating tables using ng-repeat in AngularJS and Bootstrap

Although I am new to Angular, I have been struggling with a problem for the past few days and can't seem to find a solution. I want to create a matrix of images (charts generated by angular-chart module) with 2 columns that will dynamically load a va ...

Tips for displaying HTML 5 video over an SVG element

I am currently working on a hexagon-shaped svg element that features an image as a pattern inside (depicting a worker). <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1400" height="1550" viewBox="0 0 140 155" class="svgMember memberPicLef ...

Filtering in Angular for more than 5 items in ng-Repeat

How can I filter an ng-repeat in Angular to only show values greater than 5 on a simple form? <body ng-controller="MainCtrl"> <div ng-repeat="item in items | filter:value > 5></div> <p><input type=text ng-model="item.val ...

The issue with getting a token from Next-auth on the server side persists

Currently, I am working on an application using Next.js and implementing authentication with NextAuth. However, I am encountering an issue with the getToken function not working properly on the server-side. I have double-checked my callbacks configuration ...

Testing Components in Vue: A Guide to Mocking Vue Components

I have experience using React Testing Library, but I haven't used Vue Testing Library yet. I want to avoid using mount or shallowMount when testing components in VTL and figure out how to provide a stub instead. When testing a component like Componen ...

Inquiry about unbinding in jQuery

Is it possible to use jQuery unbind() in conjunction with live()? For example: $(".content_media").unbind("touchstart").live("touchstart",function(){....}); If so, what does it actually mean? I am trying to understand the concept of unbinding elements. ...

JavaScript issue: "Error: Uncaught (in promise) SyntaxError: Unexpected end of input"

Encountering the following error message: Uncaught (in promise) SyntaxError: Unexpected end of input when attempting to post references to my specific express server. Can anyone here offer assistance? function create() { event.preventDefault() fi ...

Tips for verifying the existence of a file in a React application

I'm currently working on a Next.js React website that retrieves audio files from an API and saves them locally. My main goal is to prevent redundant API calls by checking if a file already exists before making the request. While I've found numero ...

Leveraging the Cache-Control header in react-query for optimal data caching

Is it possible for the react-query library to consider the Cache-Control header sent by the server? I am interested in dynamically setting the staleTime based on server instructions regarding cache duration. While reviewing the documentation, I didn&apos ...

How can I dynamically remove an option from a select dropdown if it already exists in another option using jQuery?

In order to achieve the desired functionality, I need to dynamically adjust the select options based on user input. Additionally, I want the selection to update automatically upon a change event. var dynamicCount = 1; $('#add').click(function ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

Trigger an Ajax request upon user confirmation, which will only be prompted based on the result of a previous Ajax call

Currently, I am facing a challenging issue surrounding asynchronous calls: A specific JQuery function is triggered on user click. This function then requests a PHP file to check if the user input overlaps with existing information in the database. If an o ...

The Jasmine test in my Angular project is experiencing a timeout issue, displaying the error message "Async callback was not invoked within 5000ms", despite the fact that no async function is being used in the

Reviewing the source code: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { IonicModule } from '@ionic/angular'; import { HomePage } from './home.page'; import { LevelGridComponent } from &a ...

Implementing TypeScript/Angular client generation using Swagger/OpenAPI in the build pipeline

Generating Java/Spring Server-Stubs with swagger-codegen-maven-plugin In my Spring Boot Java project, I utilize the swagger-codegen-maven-plugin to automatically generate the server stubs for Spring MVC controller interfaces from my Swagger 2.0 api.yml fi ...