Triggering Raphael events externally

2020-03-21 09:41发布

My app is using Raphaël to drop a collection of objects onto a page, each with a click handler bound that uses data attached to the object when it was loaded in via JSON. That’s all working fine.

I now am trying to add in some test coverage using Cucumber (yes, I know I should have built the tests in first, I will do next time). I need to trigger a click on the first object to test that that object’s associated page loads. I’ve tried finding the appropriate SVG path for that object and triggering a click event against it, but that doesn’t work. I also tried dropping each Raphaël set into a globally available object but couldn’t work out how to trigger a Raphaël click event against the appropriate one.

To give some specific questions:

1) How would one trigger a Raphaël event manually?

2) Is it possible trigger said event if you have a reference to the SVG element the Raphaël set owns?

3) If not, is it possible to access the current collection of sets Raphaël is holding?

2条回答
够拽才男人
2楼-- · 2020-03-21 10:19

You can add this custom method to your raphael elements:

Raphael.el.trigger = function(eventName){
    for(var i = 0, len = this.events.length; i < len; i++) {
        if (this.events[i].name == eventName) {
            this.events[i].f.call(this);
        }
    }
}

You can use it just like:

var r = paper.rect(0,0,100,100).attr({"fill": "#f00"});

r.click(function(){
    this.attr("fill": "#0f0");
});

r.trigger("click");
查看更多
聊天终结者
3楼-- · 2020-03-21 10:22

I found that first finding the raphael object, then traversing the DOM allowed me to find the functions of their event handlers. For mine, the click event was the 0th event.

So to trigger it all I did was:

 raphobj.events[0].f();

Be careful though, because if in the click event you reference 'this' it won't work.

查看更多
登录 后发表回答