I have gradually migrated my app from straight MVC4 to using a lot more ajax and dynamically loaded partial views. I like it, but in the process my javascript and event management have gotten a bit unweildy so I'm trying to get it more organized and maintainable. One of the things I keep tripping up on is loading events for elements that don't exist in the dom yet.
Using delegated events as described in this thread: how-should-javascript-in-an-ajax-loaded-partial-view-be-handled looks like it would help me out a lot, but I can't get it to work.
I have the following on main page load (not a partial view). In this example #maincontainer exists on page load and throughout the execution of the application. ".panetitle" is loaded later via a partial view. When it is visible, $("#maincontainer .panetitle") in devtools locates it fine. There's no other event handling involving #maincontainer
$(document).ready(function () {
$('#maincontainer').on('click', '.panetitle', function () {
console.log('clicked');
});
});
My understanding of this form of .on() is that #maincontainer needs to exist when the page is loaded, but the event should be in effect for '.panetitle' descendants of #maincontainer whenever they appear in the future. 1) Is my understanding correct? 2) Am I using it correctly? 3) Any suggestions? :)
As always, thanks. Joel