Reputation: 991
I have a ASP.NET MVC project which adopts lots of JavaScript (jQuery and d3). I am new to web development, so I want to ask for some help on how to organize front end script code.
My current way is, each folder under 'Views', has only one corresponding .js file (which means all partial views (.cshtml) under that folder, share that .js file), and I explicitly initialize all .js files of my project in $(document).ready() of _Layout.cshtml.
This introduces 2 issues:
So here are my questions:
Thanks in advance.
Upvotes: 1
Views: 1840
Reputation: 576
Split up your javascript code into multiple file such that each js file corresponds to the partial views.
Then load the corresponding js in partial view in partial view instead _Layout.cshtml file. In this way, the corresponding js will execute only when the partial view is loaded.
TypeScript is a class-based object-oriented programming style applied to basic javascript, which is developed and maintained by Microsoft. This does not help to organized the files but do help to maintain the js code in an OOP style.(link here)
KnockoutJS is Model-View-ViewModel(MVVM) pattern applied to javascript. You can modularized each js files in KnockoutJS, ie, separate js for Model, View and ViewModel but they will have dependency each other.(see documentaion)
Upvotes: 1
Reputation: 859
There are multiple ways to skin a cat. If you have javascript code specific to a partial view it's entirely fine to just skip the step of including a file and embedding JavaScript directly in there by means of the <script>
tag. This solves problem 1 and 2 you posted because razor partial views boil down to just arbitrary HTML inserted into the DOM when they are loaded.
As for TypeScript and KnockoutJS the benefits they provide are highly subjective to yourself and the project you are working on. I would suggest reading up on the features they provide and see if that's an avenue you want to pursue -- There is no right or wrong answer to this, at least not with a lot of specific context as to what you're working on.
Upvotes: 0