Accessing the prototype variable through an easeljs click event

My experience with JavaScript's prototyping is still quite new, although I am familiar with object-oriented programming in general. EaselJS is also a new territory for me. That being said, I have been struggling to get an object variable triggered by a click event and I have yet to find a satisfactory solution.

I am attempting to create a clickable 2D "board" using the following test code:

(function() { //"Class"

        Brick = function() {
            this.initialize();
        };

        var p = Brick.prototype = new createjs.Container();
        p.Container_initialize = p.initialize;

        p.initialize = function() {
            this.Container_initialize();
        };

        p.create = function(row, column) {
            this.row = row;
            this.column = column;

            //Shape
            this.square = new createjs.Shape();
            this.square.graphics.beginFill("green").drawRect(0, 0, brickSize, brickSize);
            this.x = (brickSize * column) + (Game.padding * column); // Add some padding
            this.y = (brickSize * row) + (Game.padding * row); // Add some padding
            this.addChild(this.square);

            this.addEventListener("click", function(event) { console.log(this.row)})                
        };

    })();

After this, I proceed to create a few Bricks by cycling through a multidimensional array cycle and add them to the stage. The board displays perfectly, but I keep encountering "undefined" when clicking. On the other hand, console.log(event.currentTarget.row) does work, although I am unsure if it's the correct approach.

Thank you!

Answer №1

It is advisable not to instantiate Parent in order to assign the prototype of Child. Instead, use Object.create and provide a shim for older browsers:

var p = Brick.prototype = Object.create(createjs.Container.prototype);

The event handler may have an incorrect value for this. The value of this is determined by the invoking object at the time of function invocation, not declaration. To correct this issue, you can do the following:

    p.create = function(row, column) {
        //.... no changes made
        var me = this;
        this.addEventListener("click", function(event) { 
          console.log(me.row)})                
    };

If you are using Chrome or Firefox with Firebug, it may be helpful to simply console.log(this) and click on the logged item for closer examination.

For more information about prototypes, you can visit this link.

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 there a way to convert arrow functions in vue files through transpilation?

I have developed a Vue application that needs to function properly in an ES5 browser (specifically iOS 9). One issue I've encountered is that some of the functions within the Vue components are being transformed into Arrow functions: ()=>, which i ...

Creating a slider with a large central image and just three slides that automatically transition

I am trying to create a slider that includes: 3 different images 3 different text captions A button that opens a modal dialog similar to Bootstrap, with each slide's button displaying unique text in the modal The slider should automatically slide Fo ...

Changing the model does not automatically update the visibility of ng-show

I have a fragment of my view that simply displays a loading indicator. Html: <span class="app-loading-container"> <span class="app-loading-animation" ng-show="loading"></span> </span> When I initially load the page, the span ...

Error: Unable to locate corresponding closing tag for "<%"

I'm struggling to figure out what I might have missed. Everything appears correct, but the nested and somewhat complex code that I am writing seems to be causing an issue with EJS. The variable posts has been passed from node.js to the EJS file. How c ...

Transferring information from a client-side JavaScript to a Node.js Express server and receiving back

I'm currently working on implementing an upvote and downvote system in nodejs. The functionality for upvoting and downvoting will be handled by client-side JavaScript, which will then send the data to the server for storage. I'm curious to know ...

Error displaying cookies when loading in browser

Currently, I am working on building a webpage using node.js with the hbs engine and express framework. After a user logs in, I am trying to capture cookies and use them for authentication purposes on a specific page. app.get('/path', function (r ...

Converting a lengthy HTML document into numerous JPEGs (or any preferred image format)

I am working on a lengthy webpage that can be viewed as having 40 individual pages. Each "page" is separated by a horizontal rule () and has a fixed height of 860px. My goal is to convert each of these "pages" into JPG images automatically. Can anyone pr ...

Title of button to toggle visibility using jQuery

How can I utilize jquery code to extract the text from a td? Here is my current setup: <div id="divName"> <table id="tableName"> <tr> <td id="g${req.Name}</">${req.Name}</td> <td><input type="button" id= ...

What could be causing my page to suddenly disappear?

After saving my changes in the IDE and refreshing the browser to test the prompt() function in my index.js file, the entire page goes blank, showing only a white screen. I double-checked the syntax of my function and it seems correct. Everything else on th ...

jQuery click event handler performing no action

I am encountering an issue with the input on my index page: <input type="button" name="goReplaceAll" value="Go" id="allReplaceGo" style="cursor:hand;" /> There is an onclick call from jQuery as follows: $(document).ready(function() { $(&ap ...

Run JavaScript Function from Within

Apologies for the straightforward question, but I'm struggling to find an answer anywhere. As a complete JavaScript beginner with no experience, I'm at a loss. Currently, I have a function linked to a simple button click: <input type="button ...

Excessive recursion in MooTools causing issues with Google Maps integration

Hello, I'm currently facing an issue with my WordPress plugin. Whenever Mootools is included, Google Maps are not displaying due to "too much recursion" error. Here is a snippet of the code for reference: Any suggestions or workarounds for this incon ...

Encountered an issue when trying to add content following $http .then()

Hi there, I am currently using AngularJS $http to fetch JSON data. Here is the JSON Data: {"Data":["index":[{"Name":"append_here_1"},{"Name":"append_here_2"}]]} In my App.js file: var app = angular.module('app', []); Request.js: app.service ...

Adding a checkbox to menu items in a ReactJS application can be accomplished by utilizing specific components

I have successfully created dynamic menus using a recursive function, and they are displaying in the correct order without any issues. Requirement: My current goal is to identify the last level of menus and assign a checkbox with the value corresponding ...

Testing with karma/jasmine in AngularJS can lead to issues when there are conflicts between test

Currently experiencing challenges while running my midway tests (or integration tests, which are halfway between unit tests and E2E tests). Working with an AngularJS build featuring RequireJS, I am utilizing the RequireJS plugin in Karma to run the tests. ...

Guidelines for bringing in a personal local variation of a node package

Currently in the process of developing a javascript project that relies on a kepler.gl dependency. In order to make necessary modifications to the kepler.gl source code, I am encountering difficulties importing the updated version correctly. The current s ...

Passing data in Angular 4 with eventEmitter across multiple layers of components

Struggling with a challenge in Angular and need some guidance. I am currently working with Angular 4 and here is the scenario: The app.component.html file contains a wrapper div that I want to be able to change its color by adding a class to it. However ...

The JS content failed to load into the HTML page

I need help creating a workout tracker using two JS files. The main.js file is responsible for loading content from the second file (workoutTracker.js) into the index.html. However, I'm facing an issue where the content is not being displayed on the p ...

Utilizing angular-translate efficiently within controllers

I have implemented angular-translate for internationalization in my AngularJS project. Each view in the application has its own controller where I define the value to display as the page title. Sample Code HTML <h1>{{ pageTitle }}</h1> Ja ...

Elegant method for politely asking individuals utilizing IE7 and earlier versions to leave?

TLDR: Politely ask IE6/7 users to switch browsers without accessing content. In essence, I don't want people using IE7/6 on my web app. I was considering using a doc.write function after loading to replace the page with a message stating "Sorry, your ...