Reputation: 995
Say you bind a handler to something with bind()
or on()
and specify data such as { color : "red" }
. Later on, circumstances change and you want the event to be triggered with { color : "blue"}
. Is there a way to change this without removing the handler with unbind()
or off()
and rebinding with the new data object?
Upvotes: 0
Views: 979
Reputation: 318302
No, there is no way to change this, eventData passed in can not be changed later, as that is the point, locking the data inside the event handler
var data = {test : 'test'};
$('element').on('click', data, function(e) {
// e.data will always be {test : 'test'}
});
data = {test: 'foo'}; // doesn't matter
The reason for this is that eventData was intended for cases where a closure would normally be used, like
for ( var i = 0; i < 5; i++ ) {
$("button").eq(i).on( "click", { value: i }, function( event ) {
var i = event.data.value;
// now i can be accessed with event.data.value without extra closures
});
}
so the only way to change the data is to rebind the event, or preferably use another method if you need to change the data, and you're mentioning triggering the event handler, and if you're using jQuery to do that, you can pass data that way too by using an event object inside trigger()
$('element').on('click', function(event) {
var data = event.custom;
});
$('element').trigger({
type: 'click',
custom: {color: 'red'}
});
$('element').trigger({
type: 'click',
custom: {color: 'blue'}
});
Upvotes: 4
Reputation:
I found another question that I think will help.
jQuery find events handlers registered with an object
Looks like you look at the jQuery variable directly to see what's been posted:
jQuery._data( elem, "events" );
Looks like this isn't safe and secure and I don't know if you can change it but it does let you view it.
I think it's just better to remove the event and then add the new one.
Upvotes: 0
Reputation: 2200
You could pass in a method that gets the data? i.e.
var data = {test : 'test'};
var DataGetter = function() { return data;};
$('element').on('click', DataGetter, function(e) {
var data=e.data();
});
data.test='Hello';
data = {hello: 'world'};
Upvotes: 1