Jump to content

custome Event for pixi


abbas jafari
 Share

Recommended Posts

hi friends.

I want dispatch a custom event for one sprite. 

for example:

when click on bunny sprite. dispatch an event that name is : sayHello.

i wirte this code:

Quote


const container = new PIXI.Container();

app.stage.addChild(container);

// Create a new texture
const texture = PIXI.Texture.from('examples/assets/bunny.png');

const bunny = new PIXI.Sprite(texture);
container.addChild(bunny)
bunny.anchor.set(0.5);
bunny.x = 300;
bunny.y = 200;

bunny.interactive = true;
bunny.buttonMode = true;

bunny.on('click', function(){
    const event1 = new CustomEvent('syaHello', {
        detail: {
            message: "Hello World!",
            time: new Date(),
        },
        bubbles: true,
        cancelable: true
    })
    
    this.dispatchEvent(event1)
})

document.addEventListener('sayHello', function(e){
console.log(e)

but when run and click on bunny show this error:

Quote

this.dispatchEvent is not a function

but if i change this code:

this.dispatchEvent to -> document.boy.dispatchEvent

work successfuly.

but i Want dispatch to my sprite or container . can do it????

Link to comment
Share on other sites

Hi!

Its a common Javascript newbie problem.

https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Either bind the function, either use arrow function.

bunny.on('click', () => {
   ...
});

Its not obvious, and its not something universal, for example your code could work in ActionScript ;)

Edited by ivan.popelyshev
Link to comment
Share on other sites

  • 1 month later...
On 12/17/2019 at 2:42 PM, ivan.popelyshev said:

Hi!

Its a common Javascript newbie problem.

https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Either bind the function, either use arrow function.


bunny.on('click', () => {
   ...
});

Its not obvious, and its not something universal, for example your code could work in ActionScript ;)

thanks. so now I another a question.

i want add event for just red area . can do it????

area.jpg

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...