[英]How to organize front end JavaScript code in ASP.NET MVC project?
I have a ASP.NET MVC project which adopts lots of JavaScript (jQuery and d3). 我有一个ASP.NET MVC项目,该项目采用了许多JavaScript(jQuery和d3)。 I am new to web development, so I want to ask for some help on how to organize front end script code. 我是Web开发的新手,所以我想寻求有关如何组织前端脚本代码的帮助。
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. 我当前的方式是,“视图”下的每个文件夹只有一个对应的.js文件(这意味着该文件夹下的所有部分视图(.cshtml),共享该.js文件),我明确初始化了我的所有.js文件_Layout.cshtml的$(document).ready()中的项目。
This introduces 2 issues: 这引入了两个问题:
So here are my questions: 所以这是我的问题:
Thanks in advance. 提前致谢。
Split up your javascript code into multiple file such that each js file corresponds to the partial views. 将您的JavaScript代码拆分为多个文件,以便每个js文件对应于部分视图。
Then load the corresponding js in partial view in partial view instead _Layout.cshtml file. 然后在部分视图而不是_Layout.cshtml文件的部分视图中加载相应的js。 In this way, the corresponding js will execute only when the partial view is loaded. 这样,仅当加载部分视图时,相应的js才会执行。
TypeScript is a class-based object-oriented programming style applied to basic javascript, which is developed and maintained by Microsoft. TypeScript是一种基于类的,面向对象的编程风格,应用于基本javascript,由Microsoft开发和维护。 This does not help to organized the files but do help to maintain the js code in an OOP style.(link here ) 这无助于整理文件,但有助于以OOP样式维护js代码。(链接此处 )
KnockoutJS is Model-View-ViewModel(MVVM) pattern applied to javascript. KnockoutJS是应用于JavaScript的Model-View-ViewModel(MVVM)模式。 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 ) 您可以在KnockoutJS中对每个js文件进行模块化,即分别为Model,View和ViewModel使用js,但是它们之间会相互依赖。(请参见documentaion )
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. 如果您具有特定于部分视图的javascript代码,那么只需跳过包含文件并通过<script>
标记直接将JavaScript嵌入其中的步骤就可以了。 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. 这解决了您发布的问题1和2,因为剃刀局部视图可以简化为在加载时插入DOM中的任意HTML。
As for TypeScript and KnockoutJS the benefits they provide are highly subjective to yourself and the project you are working on. 至于TypeScript和KnockoutJS,它们提供的好处在很大程度上取决于您自己和您正在从事的项目。 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. 我建议阅读他们提供的功能,看看这是否是您要追求的途径-对此没有正确或错误的答案,至少没有关于您正在从事的工作的很多特定上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.