您通常在网站中编写哪些类型的 javascript/jquery 方法?

发布于 2024-10-08 20:04:00 字数 850 浏览 6 评论 0原文

我正在为我的网站编写一个核心 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

望笑 2024-10-15 20:04:00

如果我无法从 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) );
  }
};

A logging function is one of the first things I add, if I can't start from Paul Irish's boilerplate.

// 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) );
  }
};
夏见 2024-10-15 20:04:00

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

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

I usually add a wrapper for catching any error pages.

ajaxErrorHandle: function (data, container) {
        if (data.indexOf("Server Error in '/' Application") != -1) {
            container.html(data);
            $('.ajax-loader').hide();
            return false;
        }
        return true;
    }
寻梦旅人 2024-10-15 20:04:00

我使用一些与其他语言类似的字符串格式化函数。用法:

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]);
}

I use some string formatting functions, that are similar to other languages. Usage:

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

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.

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]);
}
知足的幸福 2024-10-15 20:04:00

我使用一些方便的方法,处理动态主题,获取客户端信息以进行错误报告,并使用我的核心中的 .NET 回发处理主题问题。这里有几个片段......

    /**
    *   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

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...

    /**
    *   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
回忆追雨的时光 2024-10-15 20:04:00

我有一个很棒的跨域 ajax 和一个很棒的包装器,不幸的是我暂时丢失了它,直到我可以恢复我的 HD。事情是这样的:

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;
};

我是凭着对很久以前写过的东西的记忆来做到这一点的,但你明白了

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:

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;
};

I'm doing this by memory of stuff I wrote once long ago, but you get the point

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文