Remove event listener added with eval
I'll try and explain the best I can...
I have a page, we'll call it pageA. When a button is clicked on that page, an ajax request is sent out and the retu开发者_如何学JAVArn data is eval()'d. That data obviously contains javascript code. This code could possibly contain event listeners that are added to pageA when it is eval'd. Something like jquery $('body').click() for example.
When the button on pageA is clicked again, is there a function or something to remove any and all event listeners and data added on that eval.
I am capturing all the data returned from the ajax call into a variable before I eval the data, so is there a way to just do $(data).remove() and have all the event listeners and data magically disappear?
With eval data, it's not really added to the page per se where I could just do a text remove on the page and have all my problems go away, but the event listeners certainly do stay around.
Any ideas?
I will forgo the lecture on the evils of eval and recommend that you try namespacing your events in jQuery.
http://docs.jquery.com/Namespaced_Events
For example, have can the code in data add all new events with a namespace:
$(node).bind("click.myNameSpace", fn);
And when you want to remove it, you just do $(node).unbind("click.myNameSpace")
, of course, that's assuming you know what elements they were added to. If you don't know the type of event that was added you can also do $(node).unbind(".myNameSpace")
and it will remove all events under your namespace.
It may be easier to just copy all the currently attached event handlers on the particular button before you eval
the javascript that's returned. Then unbind all the events (to which eval
could have added extra handlers) and re-bind what was there before.
EDIT: Looks like someone's already had a similar question: jQuery: Unbind event handlers to bind them again later (though that uses jQuery).
I can't help but ask though, don't you have control over the JS that gets returned? Because if you do, it would be better to make sure malicious content is never sent in the first place.
精彩评论