新瓶旧酒ASP.NET AJAX(7) - 客户端脚本编程(Sys命名空间下的类)-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

新瓶旧酒ASP.NET AJAX(7) - 客户端脚本编程(Sys命名空间下的类)

简介:
[索引页]
[源码下载]


新瓶旧酒ASP.NET AJAX(7) - 客户端脚本编程(Sys命名空间下的类)


作者:webabcd


介绍
Sys命名空间是Microsoft AJAX Library的根命名空间。本文主要学习一下其中的Application类、ApplicationLoadEventArgs类、CultureInfo类和StringBuilder类。


关键
1、Application Class
    ·init事件 - 脚本加载完毕,对象创建之前。
    ·load事件 - 对象被创建和初始化。可以用pageLoad()
    ·unload事件 - window.unload时。可以用pageUnload()
    ·notifyScriptLoaded() - 通知ScriptManager某段脚本已经加载完毕

2、ApplicationLoadEventArgs Class
    ·components - 最后一次触发load事件时创建的Components
    ·isPartialLoad - 是否是部分刷新

3、CultureInfo Class
    ·CurrentCulture字段 - 当前的Culture,返回CurrentCulture对象
    ·name字段 - Culture的名称
    ·dateTimeFormat - 获得dateTimeFormat对象,其内有n多格式化类型
    ·numberFormat - 获得numberFormat对象,其内有n多格式化类型

4、StringBuilder Class
    ·append(text) - 添加指定字符串到StringBuilder对象的结尾
    ·appendLine() - 添加一个换行符到StringBuilder对象的结尾
    ·appendLine(text) - 添加指定字符串到StringBuilder对象的结尾并添加一个换行符
    ·clear() - 清除StringBuilder对象所有内容
    ·isEmpty() -  StringBuilder对象的内容是否为空
    ·toString() - 将StringBuilder对象的内容转换为字符串
    ·toString(separator) - 在StringBuilder对象内的每一个元素的结尾处添加指定字符串

5、其它请查看官方文档


示例
CustomButton.js
Type.registerNamespace("Demo"); 

Demo.CustomButton = function(element)    

        // 该类继承自Sys.UI.Control,调用基类构造函数 
        Demo.CustomButton.initializeBase(this, [element]); 

        this._clickDelegate = null
        this._hoverDelegate = null
        this._unhoverDelegate = null

Demo.CustomButton.prototype =    

        // 定义text属性 - 元素显示的信息 
        get_text: function()    
        { 
                // element - Sys.UI.Control的属性 
                return this.get_element().innerHTML; 
        }, 
        set_text: function(value)    
        { 
                this.get_element().innerHTML = value; 
        }, 

        // 添加或移除click事件 
        add_click: function(handler)    
        { 
                // events - Sys.Component的属性 
                this.get_events().addHandler('click', handler); 
        }, 
        remove_click: function(handler)    
        { 
                this.get_events().removeHandler('click', handler); 
        }, 
         
        // 添加或移除hover事件 
        add_hover: function(handler)    
        { 
                this.get_events().addHandler('hover', handler); 
        }, 
        remove_hover: function(handler)    
        { 
                this.get_events().removeHandler('hover', handler); 
        }, 

        // 添加或移除unhover事件 
        add_unhover: function(handler)    
        { 
                this.get_events().addHandler('unhover', handler); 
        }, 
        remove_unhover: function(handler)    
        { 
                this.get_events().removeHandler('unhover', handler); 
        }, 

        // 释放资源 
        dispose: function()    
        { 
                var element = this.get_element(); 

                if (this._clickDelegate)    
                { 
                        // Sys.UI.DomEvent removeHandler() 
                        $removeHandler(element, 'click', this._clickDelegate); 
                        delete this._clickDelegate; 
                } 

                if (this._hoverDelegate)    
                { 
                        $removeHandler(element, 'focus', this._hoverDelegate); 
                        $removeHandler(element, 'mouseover', this._hoverDelegate); 
                        delete this._hoverDelegate; 
                } 

                if (this._unhoverDelegate)    
                { 
                        $removeHandler(element, 'blur', this._unhoverDelegate); 
                        $removeHandler(element, 'mouseout', this._unhoverDelegate); 
                        delete this._unhoverDelegate; 
                } 
                Demo.CustomButton.callBaseMethod(this, 'dispose'); 
        }, 

        // 初始化 
        initialize: function()    
        { 
                var element = this.get_element(); 

                if (!element.tabIndex) element.tabIndex = 0; 

                if (this._clickDelegate === null)    
                { 
                        // Function.createDelegate用来创建一个调用“this”上下文下的特定函数的委托 
                        this._clickDelegate = Function.createDelegate(thisthis._clickHandler); 
                } 
                // Sys.UI.DomEvent addHandler() 
                $addHandler(element, 'click', this._clickDelegate); 

                if (this._hoverDelegate === null)    
                { 
                        this._hoverDelegate = Function.createDelegate(thisthis._hoverHandler); 
                } 
                $addHandler(element, 'mouseover', this._hoverDelegate); 
                $addHandler(element, 'focus', this._hoverDelegate); 

                if (this._unhoverDelegate === null)    
                { 
                        this._unhoverDelegate = Function.createDelegate(thisthis._unhoverHandler); 
                } 
                $addHandler(element, 'mouseout', this._unhoverDelegate); 
                $addHandler(element, 'blur', this._unhoverDelegate); 

                Demo.CustomButton.callBaseMethod(this, 'initialize'); 
        }, 
         
        // click事件处理器 
        _clickHandler: function(event)    
        { 
                var h = this.get_events().getHandler('click'); 
                if (h) h(this, Sys.EventArgs.Empty); 
        }, 
        // hover事件处理器 
        _hoverHandler: function(event)    
        { 
                var h = this.get_events().getHandler('hover'); 
                if (h) h(this, Sys.EventArgs.Empty); 
        }, 
        // unhover事件处理器 
        _unhoverHandler: function(event)    
        { 
                var h = this.get_events().getHandler('unhover'); 
                if (h) h(this, Sys.EventArgs.Empty); 
        } 

Demo.CustomButton.registerClass('Demo.CustomButton', Sys.UI.Control); 

// 通知ScriptManager这段脚本已经加载完毕 
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
 
 
Application.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Application.aspx.cs" 
        Inherits="ClientScripting_Sys_Application" Title="init Event和load Event和unload Event" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> 
        <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="Server"> 
                <Scripts> 
                        <asp:ScriptReference Path="~/ClientScripting/Sys/CustomButton.js" /> 
                </Scripts> 
        </asp:ScriptManagerProxy> 

        <script type="text/javascript"> 
         
                Sys.Application.add_init(applicationInitHandler); 
                function applicationInitHandler()    
                { 
                        // Sys.Component.create() 
                        $create 
                        ( 
                                Demo.CustomButton,    
                                {text: '自定义Button(Button1)'},    
                                {click: doClick, hover: doHover, unhover: doUnhover}, 
                                null,    
                                $get('Button1') 
                        ); 
                         
                        $create 
                        ( 
                                Demo.CustomButton,    
                                {text: '自定义Button(Label1)'},    
                                {click: doClick, hover: doHover, unhover: doUnhover}, 
                                null,    
                                $get('Label1') 
                        ); 
                } 

                function doClick(sender, e)    
                { 
                        Sys.Debug.trace("鼠标点击" + sender.get_id()); 
                } 
                function doHover(sender, e)    
                { 
                        Sys.Debug.trace("鼠标经过" + sender.get_id()); 
                } 
                function doUnhover(sender, e)    
                { 
                        Sys.Debug.trace("鼠标离开" + sender.get_id()); 
                } 


                Sys.Application.add_load(applicationLoadHandler); 
                function applicationLoadHandler(sender, e)    
                { 
                        alert("ApplicationLoad"); 
                        // isPartialLoad - 是否是部分刷新 
                        Sys.Debug.trace('是否是部分刷新:' + e.get_isPartialLoad()); 
                        for (var i=0; i<e.get_components().length; i++) 
                        { 
                                // components - 最后一次触发load事件时创建的Components 
                                Sys.Debug.trace('最后一次触发load事件时创建的Component:' + e.get_components()[i].get_id()); 
                        } 
                } 
                 
                 
                Sys.Application.add_unload(applicationUnloadHandler); 
                function applicationUnloadHandler()    
                { 
                        alert('ApplicationUnload'); 
                } 
                 
                 
                function pageLoad()    
                { 
                        // Sys.Application.findComponent() - 根据id查找Component 
                        // Sys.Application.findComponent(id, parent) - parent可选 
                        alert($find('Button1').get_id()); 
                } 

        </script> 

        <script type="text/javascript"> 
                function listComponents()    
                { 
                        // getComponents() - 获得所有Component(数组) 
                        var c = Sys.Application.getComponents(); 

                        for (var i=0; i<c.length; i++)    
                        { 
                                var id = c[i].get_id(); 
                                var type = Object.getTypeName(c[i]); 
                                 
                                Sys.Debug.trace('Component:' + i + ': id=' + id + ', type=' + type); 
                        } 
                } 
        </script> 

        <p> 
                <button type="button" id="Button1"> 
                </button> 
                <span id="Label1"></span> 
        </p> 
        <p> 
                <input type="button" id="Button2" value="列举所有Component" /> 
        </p> 
        <p> 
                <textarea id="TraceConsole" style="width: 500px; height: 400px;"></textarea> 
        </p> 
</asp:Content>
 
 
运行结果
1、页面加载
弹出框,信息:ApplicationLoad
是否是部分刷新:false
最后一次触发load事件时创建的Component:Button1
最后一次触发load事件时创建的Component:Label1
弹出框,信息:Button1

2、鼠标点击、经过和离开“自定义Button(Button1)”或“自定义Button(Label1)”
有相应的提示

3、单击“列举所有Component”按钮
Component:0: id=Button1, type=Demo.CustomButton
Component:1: id=Label1, type=Demo.CustomButton

4、关闭浏览器
弹出框,信息:ApplicationUnload


CultureInfo.aspx(注:设置ScriptManager的EnableScriptGlobalization="True")
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="CultureInfo.aspx.cs" 
        Inherits="ClientScripting_Sys_CultureInfo" Title="CultureInfo" Culture="auto" 
        UICulture="auto" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> 

        <script runat="Server"> 
                protected override void InitializeCulture() 
                { 
                        string s = Request.QueryString["currentculture"]; 

                        if (!String.IsNullOrEmpty(s)) 
                        { 
                                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(s); 
                                System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(s); 
                        } 
                } 
        </script> 

        <p> 
                <a href="?currentculture=zh-cn">中文</a>   <a href="?currentculture=en-us">英文</a> 
                  <a href="?currentculture=sq">阿尔巴尼亚语</a> 
        </p> 
        <div> 
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 
                <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> 
                <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label> 
                <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label> 
        </div> 

        <script type="text/javascript"> 
                // 创建一个Sys.CultureInfo对象 
                var cultureObject = Sys.CultureInfo.CurrentCulture; 
                 
                // 当前Culture的名称 
                var cultureName = cultureObject.name; 
                 
                // 获得dateTimeFormat对象 
                var dtfObject = cultureObject.dateTimeFormat; 
                 
                // 创建一个具有各种格式化类型的数组 
                var myArray =    
                [ 
                        'AMDesignator',    
                        'Calendar',    
                        'DateSeparator',    
                        'FirstDayOfWeek',    
                        'CalendarWeekRule',    
                        'FullDateTimePattern',    
                        'LongDatePattern',    
                        'LongTimePattern',    
                        'MonthDayPattern',    
                        'PMDesignator',    
                        'RFC1123Pattern',    
                        'ShortDatePattern',    
                        'ShortTimePattern',    
                        'SortableDateTimePattern',    
                        'TimeSeparator',    
                        'UniversalSortableDateTimePattern',    
                        'YearMonthPattern',    
                        'AbbreviatedDayNames',    
                        'ShortestDayNames',    
                        'DayNames',    
                        'AbbreviatedMonthNames',    
                        'MonthNames',    
                        'IsReadOnly', 
                        'NativeCalendarName',    
                        'AbbreviatedMonthGenitiveNames',    
                        'MonthGenitiveNames' 
                ]; 

                var result = '区域名称:' + cultureName; 
                 
                for (var i = 0, l = myArray.length; i < l; i++)    
                { 
                        var arrayVal = myArray[i]; 
                        if (typeof(arrayVal) !== 'undefined')    
                        { 
                                result += "<tr><td>" + arrayVal + "</td><td>" + eval("dtfObject." + arrayVal) + '</td></tr>'; 
                        } 
                } 
                var resultHeader = "<tr><td><b>格式化类型</b></td><td><b>格式化值</b></td></tr>" 
                $get('<%= Label1.ClientID %>').innerHTML = "<table border=1>" + resultHeader + result +"</table>"; 

                var d = new Date(); 
                $get('<%= Label2.ClientID %>').innerHTML = "<p/><h3>dateTimeFormat示例:" +    
                        d.localeFormat(Sys.CultureInfo.CurrentCulture.dateTimeFormat.FullDateTimePattern) + "</H3>"; 
                 
                 
                 
                // 获得numberFormat对象 
                nfObject = cultureObject.numberFormat; 
                 
                // 创建一个具有各种格式化类型的数组 
                myArray =    
                [ 
                        'CurrencyDecimalDigits',    
                        'CurrencyDecimalSeparator',    
                        'IsReadOnly',    
                        'CurrencyGroupSizes', 
                        'NumberGroupSizes',    
                        'PercentGroupSizes',    
                        'CurrencyGroupSeparator',    
                        'CurrencySymbol',    
                        'NaNSymbol',    
                        'CurrencyNegativePattern',    
                        'NumberNegativePattern',    
                        'PercentPositivePattern',    
                        'PercentNegativePattern',    
                        'NegativeInfinitySymbol',    
                        'NegativeSign',    
                        'NumberDecimalDigits',    
                        'NumberDecimalSeparator',    
                        'NumberGroupSeparator',    
                        'CurrencyPositivePattern',    
                        'PositiveInfinitySymbol',    
                        'PositiveSign',    
                        'PercentDecimalDigits',    
                        'PercentDecimalSeparator',    
                        'PercentGroupSeparator',    
                        'PercentSymbol',    
                        'PerMilleSymbol',    
                        'NativeDigits',    
                        'DigitSubstitution' 
                ]; 

                result = '区域名称:' + cultureName; 
                for (var i = 0, l = myArray.length; i < l; i++)    
                { 
                        var arrayVal = myArray[i]; 
                        if (typeof(arrayVal) !== 'undefined')    
                        { 
                                result += "<tr><td>" + arrayVal + "</td><td>" + eval("nfObject." + arrayVal) + '</td></tr>'; 
                        } 
                } 
                var resultHeader = "<tr><td><b>格式化类型</b></td><td><b>格式化值</b></td></tr>" 
                $get('<%= Label3.ClientID %>').innerHTML = "<table border=1>" + resultHeader + result + "</table>"; 
            
                var n = 99.987; 
                $get('<%= Label4.ClientID %>').innerHTML = "<p/><h3>numberFormat示例:" + n.localeFormat("C") + "<h3>"; 
                 
        </script> 

</asp:Content>
 
 
运行结果
区域名称:zh-CN
格式化类型 格式化值
AMDesignator 上午
Calendar [object Object]
DateSeparator -
FirstDayOfWeek 0
CalendarWeekRule 0
FullDateTimePattern yyyy'年'M'月'd'日' H:mm:ss
LongDatePattern yyyy'年'M'月'd'日'
LongTimePattern H:mm:ss
MonthDayPattern M'月'd'日'
PMDesignator 下午
RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
ShortDatePattern yyyy-M-d
ShortTimePattern H:mm
SortableDateTimePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss
TimeSeparator :
UniversalSortableDateTimePattern yyyy'-'MM'-'dd HH':'mm':'ss'Z'
YearMonthPattern yyyy'年'M'月'
AbbreviatedDayNames 日,一,二,三,四,五,六
ShortestDayNames 日,一,二,三,四,五,六
DayNames 星期日,星期一,星期二,星期三,星期四,星期五,星期六
AbbreviatedMonthNames 一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月,
MonthNames 一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月,
IsReadOnly true
NativeCalendarName 公历
AbbreviatedMonthGenitiveNames 一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月,
MonthGenitiveNames 一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月,

dateTimeFormat示例:2007年6月22日 8:23:27

区域名称:zh-CN
格式化类型 格式化值
CurrencyDecimalDigits 2
CurrencyDecimalSeparator .
IsReadOnly true
CurrencyGroupSizes 3
NumberGroupSizes 3
PercentGroupSizes 3
CurrencyGroupSeparator ,
CurrencySymbol
NaNSymbol 非数字
CurrencyNegativePattern 2
NumberNegativePattern 1
PercentPositivePattern 1
PercentNegativePattern 1
NegativeInfinitySymbol 负无穷大
NegativeSign -
NumberDecimalDigits 2
NumberDecimalSeparator .
NumberGroupSeparator ,
CurrencyPositivePattern 0
PositiveInfinitySymbol 正无穷大
PositiveSign +
PercentDecimalDigits 2
PercentDecimalSeparator .
PercentGroupSeparator ,
PercentSymbol %
PerMilleSymbol
NativeDigits 0,1,2,3,4,5,6,7,8,9
DigitSubstitution 1

numberFormat示例:¥99.98


StringBuilder.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="StringBuilder.aspx.cs" 
        Inherits="ClientScripting_Sys_StringBuilder" Title="StringBuilder" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> 
        <textarea id="TraceConsole" style="width: 500px; height: 300px;"></textarea> 

        <script type="text/javascript"> 
                function buildString(title) 
                { 
                        // 创建一个StringBuilder对象 
                        var sb = new Sys.StringBuilder("aaa"); 
                        // toString() - 将StringBuilder对象的内容转换为字符串 
                        Sys.Debug.trace("StringBuilder:" + sb.toString()); 
                         
                        // 添加指定字符串到StringBuilder对象的结尾 
                        sb.append("bbb"); 
                        Sys.Debug.trace("StringBuilder:" + sb); 

                        // 添加指定字符串到StringBuilder对象的结尾并添加一个换行符 
                        sb.appendLine("ccc"); 
                        Sys.Debug.trace("StringBuilder:" + sb); 
                         
                        // 添加一个换行符到StringBuilder对象的结尾 
                        sb.appendLine(); 
                        // toString(separator) - 在StringBuilder对象内的每一个元素的结尾处添加指定字符串 
                        // 然后将StringBuilder对象的内容转换为字符串 
                        Sys.Debug.trace("StringBuilder:" + sb.toString('xxx')); 

                        // 清除StringBuilder对象所有内容 
                        sb.clear(); 
                        Sys.Debug.trace("StringBuilder:" + sb); 
                         
                        // StringBuilder对象的内容是否为空 
                        var bln = sb.isEmpty(); 
                        Sys.Debug.trace("StringBuilder:" + bln); 
                } 

                function pageLoad() 
                { 
                        buildString(); 
                } 
        </script> 

</asp:Content>
 
 
运行结果
StringBuilder:aaa
StringBuilder:aaabbb
StringBuilder:aaabbbccc 

StringBuilder:aaaxxxbbbxxxccc
xxx 

StringBuilder:
StringBuilder:true


OK
[源码下载]


     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/344803,如需转载请自行联系原作者



版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章
最新文章
相关文章