Best practice for customizing JavaScript event handlers for partial views
I have a partial view that is loaded via JQuery ajax. It enumerates properties in the model and renders HTML elements that require associated JavaScript events.
Here is some simplified razor code I have now
foreach(MyObject item Model.MyObjectList)
{
string containerId = "Container" + item.Id;
string onMouseOut = "DoSomething('"+containerId+"',@Model.Id)";
<div id="@containerId" onmouseout="@onMouseOut">
//Other code here
</div>
}
This works fine, however it is often said that it is better to bind events in JQuery, if I did, you could also use JQuery events like "onmouseleave".
Thus, another way I could do is to put a script block in each enum that sets events like
<script type='text/javascript'>
$('#@containerId').mouseout(function(){
DoSomething('@containerId',@Model.Id)
});
</script>
However, this results in a lot of script block being executed.
Is there an even better solution for setting up events in partial views?
source to share
Use the .on method to bind events to things that won't always be inside the DOM.
$('#foo').on('click', function() {
// do stuff
});
Then you remove the need to embed script tags in your partials. There was a method like this which was .live () but has since been deprecated in v1.7 and removed from v1.9.
source to share