How to refer to a prototype method in JavaScript from one object to another using KineticJS

I've been experimenting with creating a method in KineticJS. Here's the code I added:

Kinetic.Circle.prototype.test = function(){
  alert(1);
}

It works well for circles, but now I'm trying to extend this method to work for layers and more. So I attempted the following code:

Kinetic.Node.prototype.test = function(){
  alert(1);
}

However, I encountered an error in my console: Uncaught TypeError: Object # has no method 'test'.

I tried searching for a solution on Google, but couldn't find one.

@EDITED For Bergi :) I have an array containing layers where I create a Kinetic.Layer object within layers[layer_name].object like so:

layers.names[name]={
  id:variable,
  object:new Kinetic.Layer()
};
stage.add(layers.names[name].object);

Yes, the stage is created before in this code:

var stage=new Kinetic.Stage({
  container:'canvas',
  draggable:true,
  height:document.documentElement.clientHeight,
  width:document.documentElement.clientWidth
});

After that, I add a point to my object in the array:

var point=new Kinetic.Circle({
  fill:'#000',
  radius:3,
  x:parent.children('input[name="x"]').val(),
  y:parent.children('input[name="y"]').val()
});
var layer_name=$('input[name="layer"]').val();
layers.names[layer_name].object.add(point).draw();

At this point, I attempt to run my method:

var layer_name=$('input[name="layer"]').val();
var point=layers.names[layer_name].object.children[$('input[name="element_index"]').val()];
point.test();

Unfortunately, all I see in the console is the error mentioned earlier.

Answer №1

It appears that Kinetic's approach to inheritance may not align with your expectations. The relationship between Kinetic.Node and Kinetic.Circle does not follow the typical prototype chain structure.

Upon creation of a Kinetic.Circle, all functions from Kinetic.Node.prototype are simply copied over using a utility function.

Although I do not personally use Kinetic, you might try implementing something like this:


var myMethods = {
    test: function() {
        alert(1);
    }
}

Kinetic.Util.addMethods(Kinetic.Circle, myMethods);
Kinetic.Util.addMethods(Kinetic.Shape, myMethods);
Kinetic.Util.addMethods(Kinetic.Node, myMethods);
Kinetic.Util.addMethods(Kinetic.Layer, myMethods);

While not as elegant as directly adding a method to the superclass's prototype, there may be valid reasons for Kinetic's chosen approach.

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

Switching from hover to click on the menu

I am struggling with adjusting the function to trigger on 'click' instead of 'hover'. I have attempted changing 'hover' to 'click' and using 'toggle' but have not seen any positive outcomes. $('#menu ...

Discover the process for breaking down JSON data into separate stages using the Express API

My API architecture is causing a problem as I try to insert it into an array called items[]. https://i.stack.imgur.com/qe802.png The setup involves a simple API built on express + mongodb. The challenge lies in figuring out how to store data from the pos ...

How can I enlarge an image on hover without disrupting the surrounding content?

After following the instructions provided on how to change image size during mouse hover, I encountered an issue where the resized image caused the rest of the content on the page to shift. Does anyone have suggestions on how to resolve this problem? ...

In the process of managing various API requests through a Node/Express middleware API, experimenting with the implementation of promise.all()

As I navigate through this project, I am stumbling upon various gaps in my knowledge. My current task involves constructing an intermediate API server. Some of the endpoints require processing an array of information, initiating external calls for each pie ...

Validating Forms using Javascript

I'm struggling to understand why I'm not getting any error or success messages when I click the submit button. My goal is to validate strings in an HTML form to ensure they are not null or too long. Both the developer's tools and the Online ...

Encountering a hydration issue in Next.js 13 due to applying initial framer-motion animation value conditionally depending on the screen size

In my Next.js 13 app, I am utilizing framer-motion for animations on a single-page layout with multiple screens. Navigation is achieved by scrolling to their respective section IDs, and I am using the traditional pages directory. One of the screens featur ...

The disappearance of node_modules results in the failure to install any dependencies for a React application, causing an error to be thrown

I've been struggling to get a react app installed, but every time I try, I encounter the following error and the entire node_modules folder disappears. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! Found ...

PHP retains the POST value even after the page is refreshed

I can't seem to shake off the persistent POST value in my HTML form, even after refreshing the page. The issue seems to be related to a login form that I am working with. To enable communication between PHP and JavaScript, I have implemented cookies ...

"Effortlessly move files with Filedrop HTML 5 and Jquery drag-and-drop feature

I am trying to implement a drag and drop file feature on my webpage, but for some reason, it's not working as expected. The drop zone is supposed to change its background color when I drag a file onto it, but that functionality doesn't seem to be ...

Iterate through elements within an HTML table by utilizing jQuery

I have a table. My goal is to loop through all the items in the table and extract their quality and price data. However, I'm struggling to access these values efficiently. Here is the structure of the table: <div class="table-items__container"&g ...

What is the best way to handle products in the second row where the price cannot be displayed in the price column?

Is there a way to effectively manage product details in the second row without displaying the price information in the designated column? https://i.sstatic.net/gac5F.png I have implemented an ajax technique to retrieve prices from the database. While the ...

Save user information to initialize rootScope upon refreshing the page

I'm looking for a way to retain a User Json Object in such a manner that I can use it to initialize my $rootScope.user Json Object with the saved information even after refreshing the page. The storage should persist as long as the browser window rem ...

What is the best way to utilize jQuery to send JSON data and then parse it on a subsequent HTML page via the

My goal is to send JSON data through the URL to the next HTML page. While testing it on an emulator for a mobile app, I encountered an issue where the URL crashed instead of redirecting to the next page. Can someone help me understand why this might be hap ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

Setting both 'a' and 'href' attributes to an existing list: best practices

I am struggling with updating my navigation bar so that the first item becomes a clickable link instead of just a list item. I attempted to add a link to the existing list item, but I think I should be using the .setAttribute method in order to achieve t ...

Can embedded HTML code communicate with Velo backend code within Wix?

I'm working on implementing a drag-and-drop feature on my website, not the file uploading kind but allowing users to move things around. I plan to use an HTML embed that will cover the entire site so I can have full control. Right now, I'm in the ...

Avoid using "out" when invoking the PHP function to access the database

I am attempting to call a PHP function from JavaScript by passing three arguments. On the PHP side, the function within the PHP file retrieves two values from the database and prints all the values. However, the code I have written does not seem to be work ...

Tips for successfully passing a variable as props within the confines of a different function's component

Is there a way to pass the variable id to the onConfirm event in this code snippet? Currently, it seems like the function is being called by another function within setAlert. How can I achieve this? const confirmationPrompt = (id) => { setAlert( ...

The customized uploading button functions seamlessly on desktop devices, yet encounters issues when used on

On my website, I have implemented a custom upload button alongside a hidden file input with the class .invisible-file-input. Here is how it is set up: Javascript $('.call-upload').click(function () { $(this).siblings('.invisible- ...

Utilizing jQuery event delegation with the use of .on and the unique reference of (

Questioning the reference in a delegated .on event: Example: $('#foo').on('click', $('.bar'), function() { console.log(this); }); In this scenario, `this` will point to #foo. How can I access the specific bar element tha ...