Reputation: 14865
ObjectI'm using in my project some lines of codes which allows me to do something like this:
<a href="#" data-click="test">Run test function</a>
And on click it will run test()
$("body").delegate( "a[data-click]", "click", function(){
var f = $(this).attr("data-click");
eval(f + "();");
});
My problem now is, that one function needs information (the jQuery Event, particular .currentTarget
) about the clicked element.
I tried with:
$("body").delegate( "a[data-click]", "click", function(event){
var f = $(this).attr("data-click");
eval(f + "(" + JSON.stringify(event) + ");");
});
But that don't works, because event
is a cycling object. (And I don't know a way to serialize the jQuery object so that I ca unserialize it and I can call the jQuery functions on it)
So how can I pass the jQuery EventObject?
Upvotes: 0
Views: 108
Reputation: 318498
No need for eval:
$("body").delegate("a[data-click]", "click", function(event) {
var f = window[$(this).data("click")];
f();
});
Note that this only works when your function is in the global scope (or available through another object which you could specify instead of window
, the global object).
Also note that you should use on
instead of delegate
:
$("body").delegate("a[data-click]", "click", function(event) { // old
$("body").on("click", "a[data-click]", function(event) { // new
Upvotes: 2