Extend the window custom object using jQuery's extend method

1. Basic knowledge

1、window.jQuery

        window.jQuery Is a global variable used to access jQuery objects in the browser. jQuery is a popular JavaScript library that is widely used to simplify tasks such as HTML document traversal, event handling, animation, and Ajax interaction.

window.jQuery You can easily use jQuery in your code         by setting  it as a variable. For example:

var $ = window.jQuery;  
  
// 使用 $ 变量访问 jQuery  
$(document).ready(function() {  
  // 在页面加载完成后执行代码  
});

        This usage typically occurs when multiple JavaScript libraries or frameworks need to be used on the same page. By  window.jQuery assigning to a new variable (such as  $), you can avoid conflicts with symbols in other libraries  $ and ensure correct use of jQuery. 

2、$.extend()

        In JavaScript, the symbol $ is usually associated with the jQuery library. .extend() is a method of jQuery that is used to merge the contents of one or more objects into the target object. This is a very useful tool because it allows you to create a new object containing the properties of multiple objects, or copy properties from one object to another.

        Basic syntax: $.extend(target, object1, object2, ...)

        in:

   a、target is the target object to which you wish to copy the properties.

         b. object1, object2, ... Is the source object whose properties you want to copy.

         Example:

var obj1 = {name: "Tom"};  
var obj2 = {age: 25};  
  
$.extend(obj1, obj2);  
  
console.log(obj1); // 输出:{name: "Tom", age: 25}

        In this example, obj1 it is the target object and obj2 it is the source object. By calling  $.extend(obj1, obj2), obj2 the properties in are copied into  obj1 , so   all properties of obj1 are included  in the end.obj2

        Note: If multiple objects have the same properties, the property values ​​of the later objects will overwrite the property values ​​of the previous objects.

3. use strict directive

        "use strict" is a directive that enables strict mode in JavaScript code. Strict mode is a special code execution mode that causes some common JavaScript behaviors to cause errors. This helps you avoid common mistakes and allows you to have more control over your code. 

        Using the "use strict" directive is as simple as adding this line of code at the top of your JavaScript file:

"use strict";

        When strict mode is enabled, JavaScript will have stricter error checking, which means that some errors that would normally be ignored will produce error messages. For example, variables must be declared, uncaught variables will generate errors, octal literals are no longer allowed, deleting variables, functions and function parameters will generate errors, etc.

Using strict mode can help you write code that is more reliable and easier to debug. It can also help you avoid unexpected behavior in production, since your code will expose more problems during development.

4. bundleconfig.jsonDocuments

        bundleconfig.json files are configuration files used with .NET Core projects to define packaging and deployment settings for your application. It is typically used in conjunction with a project's build and release process.

In  bundleconfig.json the file you can define the following:

  1. webRoot : Specifies the web root directory of the application. This is typically the entry point to the application, such as  wwwroot a directory.
  2. entryPoints : Defines the entry points of the application. You can specify the file path and generated output file name for each entry point.
  3. spaFallback : Settings for single page applications (SPA). You can specify a fallback page to use before the SPA client application loads.
  4. sourceMapMapping : Defines the path and URL of the source code mapping file. This is useful for debugging client scripts in production environments.
  5. includes : Specifies files or folders to be included in the build package.
  6. excludes : Specify files or folders to exclude from the build package.
  7. minify : Specify whether to minify JavaScript and CSS files.
  8. contentHash : Specifies whether to use content hashing for static files (such as JavaScript, CSS, images, etc.) for cache control.
  9. extensions : Specifies custom extensions to use.

The following is the content of an example  bundleconfig.json file:

[  
  {  
    "outputFileName": "wwwroot/js/site.min.js",  
    "inputFiles": [  
      "wwwroot/js/site.js"  
    ],  
    "minify": {  
      "enabled": true,  
      "renameLocals": true  
    },  
    "sourceMap": false  
  },  
  {  
    "outputFileName": "wwwroot/css/site.min.css",  
    "inputFiles": [  
      "wwwroot/css/site.css"  
    ],  
    "minify": {  
      "enabled": true  
    },  
    "sourceMap": false  
  }  
]

        In this example, two entry points are defined, one is a JavaScript file  site.jsand the other is a CSS file  site.css. The build process will compress these files and name the output files as  site.min.js and  site.min.css

5、_Form.cshtml

        _Form.cshtml is a Razor view template for generating forms, typically used in ASP.NET MVC applications. The template can contain various form elements such as text boxes, drop-down lists, radio buttons, check boxes, etc. to collect user input and submit it to the server for processing.

        Here is a simple example _Form.cshtml template that creates a form with a text box and submit button:

@using (Html.BeginForm())  
{  
    <div>  
        @Html.LabelFor(model => model.Name)  
        @Html.TextBoxFor(model => model.Name)  
    </div>  
    <div>  
        <input type="submit" value="Submit" />  
    </div>  
}

        In this example, Html.BeginForm() the method is used to create a form and  @using blocks are used to ensure that the form is closed correctly. Html.LabelFor() and  Html.TextBoxFor() methods are used to create labels and text boxes that use  properties model in the object  Name as the data source. Finally, a submit button is added to the form so that the user can submit the form.

When users view this page in a browser, they will see a form with labels and text boxes. When the user enters their name and clicks the submit button, the form data is submitted to the server for processing.

2. Examples in the Razor Framework

        This sample code and configuration is written and designed in the .NET Core MVC Razor framework. Add and bind some date and time processing functions to the window object to achieve global calling and code reuse, reducing the amount of code.

1. Create a new window member object in the wwwroot/tool/dateHelper.js file for global use

// 添加到页面的window对象上面,在页面中用dh.进行访问
; window.dh = {};

2. Use $.extend() to bind the function members to dh and register the call

(function ($, dh) {
	"use strict";
	$.extend(dh, {
		//将时间转为"yyyy/MM/dd HH:mm:ss"的格式
		getFormattedDate: function(dateParam) {
			var date = new Date(dateParam);
			var formatter = new Intl.DateTimeFormat('zh-CN', {
				year: 'numeric',
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit',
				second: '2-digit',
				hour12: false
			});
			var formattedDate = formatter.format(date);
			return formattedDate;
		},
        // 格式为 yyyy-MM-dd HH:mm:ss
        formatDate: function (v, format) {
            if (!v) return "";
            var d = v;
            if (typeof v === 'string') {
                if (v.indexOf("/Date(") > -1)
                    d = new Date(parseInt(v.replace("/Date(", "").replace(")/", ""), 10));
                else
                    d = new Date(Date.parse(v.replace(/-/g, "/").replace("T", " ").split(".")[0]));
            }
            var o = {
                "M+": d.getMonth() + 1,  //month
                "d+": d.getDate(),       //day
                "H+": d.getHours(),      //hour
                "m+": d.getMinutes(),    //minute
                "s+": d.getSeconds(),    //second
                "q+": Math.floor((d.getMonth() + 3) / 3),  //quarter
                "S": d.getMilliseconds() //millisecondjsonca4
            };
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                }
            }
            return format;
        }
    })
})(window.jQuery, window.dh);//注意调用

3. Configure the dateHelper.js file into bundleconfig.json the file

{
    "outputFileName": "wwwroot/tool/dateHelper.min.js",
    "inputFiles": [
        "wwwroot/tool/dateHelper.js"
    ],
    "minify": {
        "enabled": true,
        "renameLocals": true
    }
}

4. Dynamically generate js files through the backend to inject code and return HtmlString

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Html;
using Newtonsoft.Json;

/// <summary>
/// Adapted from https://github.com/madskristensen/BundlerMinifier/wiki/Unbundling-scripts-for-debugging
/// 
/// Areas modified:
///  - Modified it to make it work with aspnetcore.
///  - Accept both scripts and styles.
///  - Read config from wwwroot
///  - Accept baseFolder since DI not suited for static methods
///  - Style nitpicks
/// </summary>
public class BundlerHelper
{
    private static long version = DateTime.Now.Ticks;

    public static HtmlString Render(string baseFolder, string bundlePath)
    {
        string configFile = Path.Combine(baseFolder, "bundleconfig.json");
        Bundle bundle = GetBundle(configFile, bundlePath);
        if (bundle == null)
            return null;

        // Clean up the bundle to remove the virtual folder that aspnetcore provides.
        List<string> inputFiles = bundle.InputFiles;
        if (GlobalContext.SystemConfig.Debug)
        {
            inputFiles = inputFiles.Select(file => file.Replace("wwwroot", GlobalContext.SystemConfig.VirtualDirectory.ParseToString())).ToList();
        }
        List<string> outputString = bundlePath.EndsWith(".js") ?
            inputFiles.Select(inputFile => $"<script src='{inputFile}?v=" + version + "' type='text/javascript' ></script>").ToList() :
            inputFiles.Select(inputFile => $"<link rel='stylesheet' href='{inputFile}?v=" + version + "' />").ToList();

        return new HtmlString(string.Join("\n", outputString));
    }
}

class Bundle
{
    [JsonProperty("outputFileName")]
    public string OutputFileName { get; set; }

    [JsonProperty("inputFiles")]
    public List<string> InputFiles { get; set; } = new List<string>();
}

        Inject the dateHelper.min.js file into the Views/Shared/_Form.cshtml file (automatically generated by the system based on the configuration in point 3 above).

@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment

@BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/tool/dateHelper.min.js"))

5. Page call

        Create new Views/Shared/_FormWhite.cshtml. Use [@await Html.PartialAsync("_Form.cshtml")] to introduce file code and return the HTML markup of the specified partial view. .

<!--Areas文件夹下表单页面白色背景模板-->
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />

    @await Html.PartialAsync("_Form.cshtml")

    @RenderSection("header", false)
    <script type="text/javascript">
        var ctx = '@Url.Content("~/")';
    </script>
</head>
<body class="white-bg">
    @RenderBody()
    @RenderSection("footer", false)
</body>
</html>

        Introduce the _FormWhite.cshtml file into the required page (such as: TestForm.cshtml), and you can use the function methods in window.dh.

@{
    Layout = "~/Views/Shared/_FormWhite.cshtml";
}

<div></div>

<script type="text/javascript">
    //调用window.dh中绑定的方法
    var date = dh.getFormattedDate(new Date());
</script>

Guess you like

Origin blog.csdn.net/weixin_50478033/article/details/133210540