你常常在网站中编写哪些JavaScript/jQuery方法?

10

我正在编写一个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.method来执行各种任务……几乎将所有javascript代码移到一个可以被缓存的.js文件中。

只是出于好奇,你在网站中构建了哪些常见函数?


那是什么意思?我该如何发布到维基上? - Chaddeus
现在只有版主可以将帖子设为维基页面。我已经标记了它,等待版主处理。 - Josh Leitzel
现在它可以用于这样的对话,因此更适合程序员在 Stack Exchange 上使用。 - user1228
好的,我会在那里添加它。 - Chaddeus
@Will,我在程序员SE上发布了这个问题,但被关闭了。 :D - Chaddeus
显示剩余2条评论
5个回答

4

如果我不能从Paul Irish的模板开始,那么日志记录功能就是我添加的第一件事。

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

3

我通常添加一个包装器来捕获任何错误页面。

ajaxErrorHandle: function (data, container) {
        if (data.indexOf("Server Error in '/' Application") != -1) {
            container.html(data);
            $('.ajax-loader').hide();
            return false;
        }
        return true;
    }

很酷,所以你不返回包含成功标志的JSON对象,而是检查返回数据字符串是否以错误消息开头?对于那些只想返回小块HTML而不是JSON的情况来说,这不是一个坏主意。 - Chaddeus

2

我使用一些字符串格式化函数,它们类似于其他编程语言。用法:

var s = 'Hello {0}!'.format('World'); // result is "Hello World!"
var person = { Name: 'Will' };
var greeting = 'Hello {Name}!'.formatWith(person); // result is "Hello Will!";

以下是函数定义。我在很多地方都使用了简单版本的map和reduce,尤其是在内部网站上,我会充分利用Javascript。

String.prototype.format = function ()
{
    var pattern = /\{\d+\}/g;
    var args = arguments;
    return this.replace(pattern, function (capture) { return args[capture.match(/\d+/)]; });
}

String.prototype.formatWith = function (obj, clean)
{
    return this.replace(/\{(.*?)\}/gim, function (all, match) { return obj[match]; });
}

function reduce(fn, a, init, limit)
{
    var s = init;
    var l = (limit == undefined) ? a.length : Math.min(a.length, limit);
    for (i = 0; i < l; i++)
        s = fn(s, a[i], i);
    return s;
}

function map(fn, a)
{
    var l = a.length;
    for (i = 0; i < l; i++)
        a[i] = fn(a[i]);
}

你可能想在现代浏览器中使用默认的数组映射和归约方法。请查看 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map 和 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce。 - dheerosaur
不错,我有一个函数也可以进行正则属性匹配...但只在需要多次匹配相同令牌时使用。否则,我会使用上面展示的str.replace方法...它更快。 - Chaddeus

1

我在我的核心中使用一些便捷方法,处理动态主题,获取客户端信息以进行错误报告,并处理.NET Postbacks中的主题问题。以下是一些片段...

    /**
    *   A convenience method for notifications that can be 
    *   called anywhere in the app, in place of standard 
    *   javascript alerts.  Assuming you define CSS for 
    *   the ID and/or are using jQuery UI, these alerts 
    *   are skinned.
    *
    *   @param string - the message that you want to display
    *   @example - alert('Hello World');
    */
    alert: function(msg) {
        $('body').append('<div id="alert">' + msg + '</div>');
        $('#alert').dialog({
            bgiframe: true
            , modal: true
            , width: 400
            , buttons: {
                Ok: function() { $(this).dialog('destroy'); }
            }
        });
        return this;
    } // EO alert


    /**
    *   .NET Event Handlers
    *   When new code is added on to the client by way of
    *   .NET PostBacks, CSS is typically ignored.  This method
    *   can be used to add CSS to new elements as they are added
    *   asynchronously.  It calls a script at the end of every 
    *   partial post back request.
    *
    *   @example - Core.NETEventHandlers.AsyncPostBack.Init();
    */
    , NETEventHandlers: {
        /**
        *   Async Post Back Handler
        *   calls a script at the end of every partial post back request
        */          
        AsyncPostBack: {
            EndRequest: {
                Add: function() {
                    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Core.NETEventHandlers.AsyncPostBack.EndRequest.Handler); // where Core.NET... leads to this method
                } // EO Add
                , Handler: function(sender, args) {
                    // Handlers here.  Consider adding them into a separate method
                    alert('Hello World');
                } // EO Handler
            } // EO endRequest
            , Init: function() {
                Sys.Application.add_init(Core.NETEventHandlers.AsyncPostBack.EndRequest.Add);   // where Core.NET... leads to this method
            }
        } // EO AsyncPostBack
    } // EO dotNETEventHandlers

很好,谢谢分享。现在我在我的 Web 应用程序中使用 ASP.NET MVC... 当我使用 ASP.NET 时,这会很不错。 - Chaddeus

0

我之前曾有一个很棒的用于跨域ajax的封装,可惜现在暂时丢失了,要等我恢复硬盘才能找回。不过大概是这样的:

ajax = function(site, callback) {
    $.getScript('get.php?url=' + escape(site) + '&callback=' + callback);
}

ajax.find = function(url) {
    ret = [];
    if (url.match) {
        for (var i = 0; i < this.length; i++)
            if (url.match(this[i].url))
                ret.push(this[i]);
    }
    else
        for (var i = 0; i < this.length; i++)
            if (url === this[i].url)
                ret = this[i];
    return ret;
};

我是凭记忆写的,很久以前写过类似的东西,但你明白我的意思。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接