I am in the process of moving my partial views to view components, as components according to Microsoft is significantly better than partial views, especially at handling complex views..
For the partial views that I'm now porting to view components, I have a lot of jQuery script. Normally I invoke my jQuery components in my $(document).ready()
function like so:
$(document).ready(function(){
Component1.init();
Component2.init();
....
})
This logic was very useful because these views have to be updated several times. Therefore, when having partial views, the components were re-initialized because the $(document).ready()
function would always fire when the partial view document was ready after update.
However, moving to view components, I still try to do the same. Unfortunately, I realized that the $(document).ready()
is only fired the first time that the view component is ready - Meaning that, when updating the view component, the $(document).ready()
function is not fired and hence not the jQuery components initialized. I'm using a standard Ajax call to target a controller which returns the viewcomponent - Everything works fine, except that the $(document).ready()
function isn't fired after update.
Note
A workaround would be to initialize my components in the ajax success response. This works but is however not desirable.
- What is going on here?
- Why does my
$(document).ready()
function not fire after updating the view component? - How would I correctly solve this, so that all my jQuery components gets initialized once the view component is ready?
Example:
//view with component
<div id="Component">
<vc:mycomponent lead="Model.Lead"></vc:mycomponent>
</div>
//Script Inside component
<script>
$(document).ready(function () {
Component.init();
});
var Component = (function () {
var $button;
var $component
var init = function() {
cacheDom();
handlers();
}
var cacheDom = function(){
var $button = $('#button1')
var $component = $('#Component')
}
var handlers = function () {
$button.on('click', function() {
handleclick();
})
}
var handleClick = function(){
$.ajax({
url: 'Controller/ViewComponent',
type: 'GET',
success: function (response) {
$component.html(response);
}
});
}
return {init : init}
})
</script>