您通常在网站中编写哪些类型的 javascript/jquery 方法?
我正在为我的网站编写一个核心 javascript 对象,构建我使用的常用方法(并包装一些 jQuery 方法)。
它的构建方式如下:
var Core = {
baseUrl: '/',
lang: 'en-us',
loggedIn: false,
msg: function(str) {
for (var i = 1, len = arguments.length; i < len; ++i) {
str = str.replace("{" + (i - 1) + "}");
}
return str;
},
include: function(url, success, cache) {
$.ajax({
url: url,
dataType: 'script',
success: success,
cache: cache !== false
});
},
etc...
}
msg 是一种模仿 C# String.Format 的方法,include 让我可以异步引入脚本。还有其他(formatDate:将日期时间字符串转换为用户的本地时间,getBrowser:根据功能检测获取浏览器类型,open:打开链接在新窗口中等...)
这个核心对象让我可以执行多种任务...只需调用 Core.方法...将几乎所有的 javascript 代码移动到 . js 文件可以被缓存。
出于好奇,您在网站中构建了哪些常见功能?
I'm coding a core javascript object for my site, building in the common methods I use (and wrapping a few jQuery methods as well).
It's built like this:
var Core = {
baseUrl: '/',
lang: 'en-us',
loggedIn: false,
msg: function(str) {
for (var i = 1, len = arguments.length; i < len; ++i) {
str = str.replace("{" + (i - 1) + "}");
}
return str;
},
include: function(url, success, cache) {
$.ajax({
url: url,
dataType: 'script',
success: success,
cache: cache !== false
});
},
etc...
}
msg is a method to mimic C# String.Format, include lets me asynchronously pull in scripts. There are others (formatDate: converts datetime string to user's local time, getBrowser: gets browser types based on feature detection, open: opens a link in a new window, etc...)
This core object lets me perform a wide array of tasks... by just calling Core.method... moving nearly all of my javascript code into a .js file which can be cached.
Just out of curiousity, what sorts of common functions do you build into your sites?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果我无法从 Paul Irish 的样板 开始,那么日志记录功能是我首先添加的功能之一。
A logging function is one of the first things I add, if I can't start from Paul Irish's boilerplate.
我通常添加一个包装器来捕获任何错误页面。
I usually add a wrapper for catching any error pages.
我使用一些与其他语言类似的字符串格式化函数。用法:
这是函数定义。我还在各处使用简单版本的map和reduce,在外部网站上用得不多,但在内联网上我全力以赴使用Javascript。
I use some string formatting functions, that are similar to other languages. Usage:
And here's the function definitions. I also use simple versions of map and reduce all over the place, not so much on external sites, but on an intranet I go all out with Javascript.
我使用一些方便的方法,处理动态主题,获取客户端信息以进行错误报告,并使用我的核心中的 .NET 回发处理主题问题。这里有几个片段......
I use some convenience methods, handle dynamic theming, grab client info for error reporting and handle theming issues with .NET Postbacks in my core. Here are a couple snippets...
我有一个很棒的跨域 ajax 和一个很棒的包装器,不幸的是我暂时丢失了它,直到我可以恢复我的 HD。事情是这样的:
我是凭着对很久以前写过的东西的记忆来做到这一点的,但你明白了
I had a great one for cross-domain ajax with an awesome wrapper, unfortunately I lost it for the moment until I can restore my HD. It was something like this though:
I'm doing this by memory of stuff I wrote once long ago, but you get the point