Wic*_*ams 31 javascript maintainability jquery document-ready
注意:我现在已经创建了一个jQuery插件,这是我尝试解决这个问题.我相信它可以改进,我可能忽略了很多用例,所以如果有人想提供反馈请随意:-) https://github.com/WickyNilliams/ReadyBinder
我没有这样的问题,但认为这将是一个有趣的讨论点,我希望人们对此有一些有趣的想法.
基本上,我在一个大型网站上工作,我们越来越多地编写越来越多的JavaScript.这很好,我喜欢JS独特的方法,我发现在语言的一些较暗的年代中可爱的奇怪之处;-)然而,一直困扰我的一件事是如何管理文档就绪事件,因为它们变得越来越大随着时间的推移(因此对于所服务的页面不太专注/特定)
问题是我们有一个JS文件(合并和缩小,虽然这对我的问题有点无关紧要).大多数JS都是使用揭示模块模式编写的,jQuery是我们选择的框架.所以我们所有的JS功能都在逻辑上分组为方法,命名空间,然后在脚本文件的底部我们有这个
$(function(){
//lots of code here, usually calling encapsulated methods
//on our namespaced revealing module
});
Run Code Online (Sandbox Code Playgroud)
问题是并非本文档就绪处理程序中的所有代码都与每个页面相关.例如,在一个页面上只有10%可能是相关的,在另一个页面上,80%可能是相关的.对我来说,这感觉非常错误,我觉得我应该只执行每页需要的代码,主要是为了提高效率,还要保持可维护性.
我搜索谷歌搜索这个问题的方法,但找不到任何东西,也许我只是在寻找错误的东西!
无论如何,所以我的问题是:
期待人们对此事的看法.
干杯
这是我在我的rails mvc项目中用大量的javascript做的,我为js中的控制器创建了一个单独的命名空间,类似于rails控制器
class BusinessController
def new
end
def index
end
end
Run Code Online (Sandbox Code Playgroud)
和
Var Business = {
init : function(action) {
//code common to the Business module
//even add the common jquery doc ready here, its clean
//and call the page specific action
this[action]();
},
new : function() {
// check jquery document ready code here, thats relevant to this action
//New rental page specific code here
},
index : function() {
// check jquery document ready code here, thats relevant to this action
//index rental page specific code here
}
}
Run Code Online (Sandbox Code Playgroud)
并且在视图代码(服务器端)上只需启动页面特定的js代码
<script type="text/javascript">
<%= controller_name %>.init('<%= controller.action_name %>');
//which will render to
// Business.init(index);
</script>
Run Code Online (Sandbox Code Playgroud)
您可以调整它以使其适用于任何语言.这种方法并不关心您是单个文件还是多个文件.
| 归档时间: |
|
| 查看次数: |
1327 次 |
| 最近记录: |