如何基于页面分离jQuery事件监听器? [英] How to separate jQuery event listeners based on page?

查看:78
本文介绍了如何基于页面分离jQuery事件监听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是有一个案例,我有一个.js文件,其中包含我网站上许多页面的事件处理程序,如下所示:

I alway have a case where I have one .js file which contain event handlers for many pages in my website, something like this:

$(function () {  
$('#my-textbox1').click(function(){ doSomthing(); }) //--> this my-textbox1 exists in page example1.aspx  
$('#my-textbox2').click(function(){ doSomthing(); }) //--> this my-textbox2 exists in page example2.aspx  
});

现在假设用户打开了页面example1.aspx,jquery将搜索my-textbox1,如果找到它将附加一个click事件,然后将搜索my-textbox2并且找不到它并且不会附加事件。

Now suppose the user opened page example1.aspx, jquery will search for my-textbox1 and if found it will attach a click event to it, then will search for my-textbox2 and will not find it and will not attach the event.

但是像所有情况下的jquery一样在所有页面中搜索my-textbox2,

But like this jquery in all cases will search for my-textbox2 in all pages,

我想知道的最佳做法是避免在不需要它们的页面中调用不需要的选择器。

What I want to know is the best practice you do to avoid unwanted selectors to get called in pages that don't want them.

可能这不是2个事件的大问题,但假设我有数百个事件想要附加,这肯定会影响页面加载性能。 / p>

May be it is not a big problem with 2 events, but suppose i have hundreds of events want to attach, this will affect the page load performance for sure.

推荐答案

在我们的项目中,我们总是使用基于身体类的视图模式。这是一个规定的示例:

In our projects, we always use a view pattern based on body classes. Here is a stipped down example:

views = {
  home: function() {
    // do stuff on home page
  },
  products: function() {
    // do other stuff on products page
  }
};

$.each(document.body.className.split(' '), function() {
  if (this in views) {
    views[this]();
  }
});

这篇关于如何基于页面分离jQuery事件监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆