I´m holding back some of my native click events on hyperlinks, to check if the result page holds a content.
Im saving the jquery event object and after some checkings, i want to let the event go its natural way.
- Capture Event
- Check for Contents
- If contents available
- forward event as it was fired
- else
- do nothin
At this moment, I just saving the "href"
property and want to set it to the document.location.href
if true comes back.
Now, the question: Is there a 开发者_如何学Cbetter way to forward/reraise the existing event, than setting the href to the document.location.href
?
Using document.location.href
would be fine, and also seems like the simplest option to me.
But just for the sake of exploring other options, you could also have js click the link for you if it's deemed as safe. For example, something like this.
$('a').click(function() {
if( !$(this).is('.content-verified') ) {
var self = this;
// Do your content checking here, with the callback for verified good
// content being $(self).has_good_content();
return false;
}
return true;
});
// Callback for good content
// should be something like this:
$.fn.has_good_content = function() {
return $(this).each(function() {
$(self).addClass('content-verified');
$(self).click();
});
};
This sounds like a job for the jQuery Deferred object. New in jQuery 1.5+
function done() {
var dfd = $.Deferred(),
timeout;
timeout = setInterval(function() {
if (contents available) {
clearInterval(timeout);
return dfd.resolve();
}
}, 50);
return dfd.promise();
}
$('#my-link').bind('click', function(e) {
e.preventDefault();
var $this = $(this);
$.when(done())
.then(function(o) {
//unbind the click event that prevents the default action and click on the link afterward
$this.unbind('click').click();
});
});
So what is happening is it will wait for the resolve/success state from the done
function. You are telling your click event to wait because done
is using the Deferred object and has promised to return something.
I have put a setInterval
to check every 50 mili seconds if the contents have loaded then I resolve
the Deferred object therefore the then
in click event will be called.
You can pass an object to dfd.resolve();
like this dfd.resolve({ test: true });
. Then the o
argument in then
will have o.test
.
I have used Deferred several times and I really liked it.
Hope this helps
精彩评论