In ASP.NET MVC, what is the preferred pattern for running Javascript on a partial view that is loaded via Ajax?
For example, suppose you need to wire up some click events in your partial view.
Of course, putting something like this in the partial view would not work, because the document ready event won't fire after the partial view is Ajax loaded.
<script type="text/javascript">
$(function() {
$("a.foo").click(function() {
foo();
return false;
});
});
</script>
I suppose something like this might work, but is it safe?
<script type="text/javascript">
$("a.foo").click(function() {
foo();
return false;
});
</script>
The pattern I have been using has been to run any Javascript from my parent view after loading the partial, like this:
$.get(url, function(html) {
$("#partialDiv").html(html);
// Now that the partial has loaded...
RegisterClicks();
});
But I've been working through this example, and noticed that they simply put their click registering code inline in the partial view.
Is this a generally safe pattern to adopt? How can I be sure that the DOM for the partial view has finished loading before my script runs?
The jQuery .on() function should do the trick, shouldn't it? It should work for dynamically added content.
Have this available as part of the full content
<script type="text/javascript">
$(function() {
$("#partialContent").on("click", "a.foo", function() {
foo();
return false;
});
});
</script>
<div id="partialContent">
<a href="#" class="foo">Link 1</a>
<a href="#" class="foo">Link 2</a>
<!-- More dynamic content -->
</div>