How to auto bind plugin initializations for content loaded through ajax
I'm using expandable plugin by Brandon Aaron to auto grow my textareas in the form and it is working ok. the problem is that I'm loading a lot of pages through ajax so I need to rebind the plugin method to the textareas loaded through ajax.
i开发者_如何学Cs there a way to do this kind of method calls like
$("textarea").expandable();
through live() or delegate() in jQuery. it'll make my code much cleaner.
The .liveQuery
plugin still has a use here, it's not entirely replaced by jQuery core's .live()
, here's how your example would work:
$("textarea").liveQuery(function() {
$(this).expandable();
});
.livequery()
actually watches for new elements, unlike .live()
which listens for events to bubble up the DOM, they operate in very different ways.
Only events can be binded, plugins have to be called with every new element.
[Edit]
Events aren't binded to new elements, the events are just caught on the bubbling/capturing phase on the way to the element, allowing for new elements to be added and events can still be handled.
Plugins are binded to the element set returned by the init constructor. It is up to plugin developers to use event delegation within their plugin to capture new elements being added within the element scope they were attached to (or they can go outside to the document and risk clashing with other plugins).
The way I would personally go about this is have the plugin initialize in a function and call that function when the ajax load is completed.My laptop battery is low so my syntax is probably a little off but the idea is there.
function foo()
{
$('.classSelector').plugin();
}
$('.eventListener').load('url', function()
{
foo();
})
精彩评论