Reputation: 173
I'm building a plugin to submit forms with jQuery.
It needs to work with live elements, so I need to use $(document).on();
Here is an example of what I'm trying to accomplish:
$.fn.submittable = function() {
$(document).on('submit', this, function(event) {
event.preventDefault();
//Do whatever
});
};
$(document).ready(function() {
$('.tosubmit').submittable();
});
But $(this)
doesn't seem to work with .on()
if I do, $(this).submit(function(event) {});
it works fine.
Am I doing something wrong?
Upvotes: 0
Views: 147
Reputation: 173
I'm not sure I explained the issue well enough. The replies to this question suggested this was bad practice, and I was not sure why. However I just found the solution and all is now clear to me.
When using plugins with live content, the plugin must be loaded inside the $.post
or .get
function like so.
$.post('.').done(function(data) {
$('.to-call-on').plugin();
});
Upvotes: 1
Reputation: 339826
The delegated version of .on
requires that the selector
parameter be a string, not an element (or in your case, a jQuery object, that being what this
is within a jQuery plugin).
Why use delegation at all, though?
$.fn.submittable = function() {
return this.on('submit', function(event) {
event.preventDefault();
...
});
};
and then just invoke that on your newly-loaded content after each AJAX call.
Upvotes: 3
Reputation: 700372
Use the selector
property to get the selector that was used to create the jQuery object:
$.fn.submittable = function() {
$(document).on('submit', this.selector, function(event) {
event.preventDefault();
//Do whatever
});
};
Note: This makes your plugin work in the way that the jQuery live
method did. That way of binding events was abandoned because the syntax is a bit awkward and can cause confusion. You should consider using a syntax more like the one the on
method uses for delegation:
$.fn.submittable = function(selector) {
this.on('submit', selector, function(event) {
event.preventDefault();
//Do whatever
});
};
Usage example:
$(document).submittable('.tosubmit');
Upvotes: 1