One question I ask myself for a long time: below are 2 methods for passing parameters from my view to my javascript:
Method 1:
My view:
<script type="text/javascript">
tabChangeConfirmationTitle = "@Html.Raw(UserResource.Warning)";
tabChangeConfirmationMessage = "@Html.Raw(UserResource.TabChangeConfirmationMsg)";
</script>
My javascript file:
var tabChangeConfirmationTitle;
var tabChangeConfirmationMessage;
Method 2:
My view:
<script type="text/javascript">
fctTranslationsForConfirmationDialog("@Html.Raw(UserResource.Warning)", "@Html.Raw(UserResource.TabChangeConfirmationMsg)");
</script>
My javascript file:
var tabChangeConfirmationTitle;
var tabChangeConfirmationMessage;
function fctTranslationsForConfirmationDialog(Title, Message) {
tabChangeConfirmationTitle = Title;
tabChangeConfirmationMessage = Message;
}
I prefer the 1st method. Is it a good one? Is there a better method?
Thanks.
PS: I know there are othere related questions but I would like your opinion on these two methods.
I would go for a variation on method 1:
js file:
in your html head:
this way your html doesn’t contain as much javascript and if you ever want to add more variables it’s very clean and easy how to do that; just add the variable to your p object in your js file and initialize it in your onload handler. Any other javascript then the onload initialization code can go in your js file and it doesn’t get cluttered by non javascript code.
Also, by using the p object you create a namespace and avoid polluting the global namespace with more than 1 object.