Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire event in Raphael.js

I have an Raphael element with click event handler:

var paper = Raphael("container", 770, 160);
var c = paper.rect(10, 10, 50, 50);
c.click(function () {
    alert("triggering");
})

How I can manually fire this event? (c.click() don't work)
Thanks!

like image 572
Artur Keyan Avatar asked Aug 14 '12 11:08

Artur Keyan


4 Answers

Although this question is already answered, I will post my solution which I found out by random. It's possible with the Raphael internals:

When you attach an event listener like element.click(func) then the element object holds an array with all events. In this array there's an object which has a method f (strange naming convention) which triggers the event.

So to sum it up you can call your event with knowing the order of your events, in your case there's just the click event which is on index 0, you can call it like: c.events[0].f();

A more generic solution would be a function like

function triggerClick(element) {
    for(var i = 0, len = element.events.length; i < len; i++) {
        if (element.events[i].name == 'click') {
            element.events[i].f();
        }
    }
}​

But beware that if you had multiple click events all were triggered.

Here's a fiddle to demonstrate.

like image 184
dan-lee Avatar answered Oct 24 '22 15:10

dan-lee


Even though this has already been answered a while ago, I was looking for something a little "more native" in nature. Here's how I go about it without relying on Mootools or jQuery.

var evObj = document.createEvent('MouseEvents'); 
evObj.initEvent('click', true, false); 
c.node.dispatchEvent(evObj); 

This basically creates the event in the browser and then dispatches it to the node associated with the Raphaël object.

Here's also the MOZ link for reference: https://developer.mozilla.org/en-US/docs/DOM/document.createEvent

like image 43
Jason Wiener Avatar answered Oct 24 '22 15:10

Jason Wiener


I actually found a slightly more elegant way to use Kris' method. Raphael supports native extension of the element object so I built a little patch to add the trigger method to raphael

here it is:

//raphael programatic event firing
    Raphael.el.trigger = function (str, scope, params){ //takes the name of the event to fire and the scope to fire it with
        scope = scope || this;
        for(var i = 0; i < this.events.length; i++){
            if(this.events[i].name === str){
                this.events[i].f.call(scope, params);
            }
        }
    };

I set up a Js fiddle to show how it works: here

like image 25
8-bit Tom Avatar answered Oct 24 '22 14:10

8-bit Tom


EDIT :

The solution purposed by Dan Lee is working better.

like image 35
Charles Jourdan Avatar answered Oct 24 '22 13:10

Charles Jourdan