javascript ES6 +

ES6
// Trick to destructure more than 1 property of an object in diff nested lvl
const { history: { action, location: { pathname }  } } = props;

javascript Webpack配置

webpack.config.js
var path = require('path');
var glob = require('glob-all');
var webpack = require('webpack');
var inProduction = true;
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var PurifyCSSPlugin = require('purifycss-webpack');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var extractSass = new ExtractTextPlugin({filename: '[name].[contenthash].css'});

module.exports = {
  entry: './app/Resources/assets/js/vue/bootstrap.js',
  output: {
    filename: 'bundle.[hash].js',
    path: path.resolve(__dirname, './web/build'),
  },
  node: {
    fs: 'empty',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
        use: extractSass.extract({
          use: [
            {
              loader: 'css-loader',
              options: {
                url: true,
              },
            },
            {
              loader: 'postcss-loader',
              options: {
                plugins: function() {
                  return [
                    require('precss'),
                    require('autoprefixer'),
                  ];
                },
              },
            },
          ],
          fallback: 'style-loader',
        }),
      },
      {
        test: /\.scss$/,
        use: extractSass.extract({
          use: [
            {
              loader: 'css-loader',
              options: {
                url: true,
              },
            },
            {
              loader: 'postcss-loader?sourceMap',
            },
            {
              loader: 'sass-loader',
            }],
          fallback: 'style-loader',
        }),
      },
      {
        test: /\.(png|jpg|gif)$/,
        loader: [
          {
            loader: 'url-loader?limit=1000',
            options: {
              limit: 8192,
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new BrowserSyncPlugin({
      host: 'localhost',
      port: 3000,
      proxy: 'orange.dev',
    }),
    new CleanWebpackPlugin([
      path.join(__dirname, 'web/build'),
    ], {
      exclude: [],
      verbose: true,
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: inProduction,
    }),
    function() {
      this.plugin('done', stats => {
            require('fs').writeFileSync(
                path.join(__dirname, 'app/Resources/assets/manifest.json'),
                JSON.stringify(
                    {
                      jsBundle: stats.toJson().assetsByChunkName.main[0],
                      cssBundle: stats.toJson().assetsByChunkName.main[1],
                    },
                ),
            );
          },
      );
    },
    extractSass,
    new PurifyCSSPlugin({
      paths: glob.sync([
        path.join(__dirname, 'app/Resources/views/*/*/*.html.twig'),
        path.join(__dirname, 'app/Resources/views/*/*.html.twig'),
        path.join(__dirname, 'app/Resources/views/*.html.twig'),
        path.join(__dirname, 'src/ShopBundle/Resources/views/*.html.twig'),
        path.join(__dirname, 'src/ShopBundle/Resources/views/*/*.html.twig'),
        path.join(__dirname, 'src/ShopBundle/Resources/views/*/*/*.html.twig'),
      ]),
      minimize: inProduction,
      purifyOptions: {
        whitelist: [
          '.default-dropdown',
          '.active',
          '.selection',
          '.dropdown',
          '.menu',
          '.focus',
          '.no-pic'
        ],
      },
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: (inProduction)
            ? JSON.stringify('production')
            : JSON.stringify('development'),
      },
    }),
  ],
};

if (inProduction) {
  module.exports.plugins.push(
      new webpack.optimize.UglifyJsPlugin(),
  );
}

javascript 按国家/地区代码设置默认时区

fix_time_zone_by_country
/* Script to set default time zone */
var gr = new GlideRecord("sys_user");
gr.addQuery('email', 'amrik.singh@uk.fujitsu.com');  //TEST
gr.addEncodedQuery("active=true^u_person_type=Employee^countryINDK,EE,FR,DE,PT,FI,IT,IE,GB,PL,ES,NO,SE,TR^time_zone=");
//gr.addQuery("u_country","");
//gr.setLimit(25);
gr.query();
while (gr.next()) {
                switch (gr.country.toString()){
                case "GB":
                                gr.time_zone = "GMT";
                                break;
                case "IE":
                                gr.time_zone = "GMT";
                                break;
                //Poland
                case "PL":
                                gr.time_zone = "Europe/Warsaw";
                                break;
                //Finland
                case "FI":
                                gr.time_zone = "Europe/Helsinki";
                                break;
                //Estonia
                case "EE":
                                gr.time_zone = "Europe/Helsinki";
                                break;
                //Sweden
                case "SE":
                                gr.time_zone = "Europe/Stockholm";
                                break;
                //Norway
                case "NO":
                                gr.time_zone = "Europe/Oslo";
                                break;
                //Denmark
                case "DK":
                                gr.time_zone = "Europe/Copenhagen";
                                break;   
                //Spain
                case "ES":
                                gr.time_zone = "Europe/Madrid";
                                break;
                //Portugal
                case "PT":
                                gr.time_zone = "Europe/Lisbon";
                                break;
                //Italy
                case "IT":
                                gr.time_zone = "Europe/Rome";
                                break;
                //Turkey
                case "TR":
                                gr.time_zone = "Europe/Istanbul";
                                break;
                //France
                case "FR":
                                gr.time_zone = "Europe/Paris";
                                break;
                //Germany
                case "DE":
                                gr.time_zone = "Europe/Berlin";
                                break;
}
                gr.setWorkflow(false);
                gr.autoSysFields(false);
                gr.update();
}
gs.info("CJT Updated");

javascript 用于修复数据的HR背景脚本

background_HR_fixes
/* Set all HR Cases with no Country code to have a country code equal to opened_for user */
var gr = new GlideRecord("hr_case");
gr.addQuery('number', 'HRC0047687');
gr.addEncodedQuery("u_countryISEMPTY");
//gr.addQuery("u_country","");
gr.query();
while (gr.next()) {
	//gs.info("CJT Country:"  + gr.opened_for.country.toString());	
	var gr_country = new GlideRecord("core_country");
	gr_country.addQuery("iso3166_2",gr.opened_for.country.toString());
	gr_country.query();
	while(gr_country.next()){
		//gs.info("CJT core country:" + gr_country.name.toString());
		gr.u_country = gr_country.sys_id;
		gr.setWorkflow(false);
		gr.autoSysFields(false);
		gr.update();
	}
	

}
gs.info("CJT Updated");



/* Set Users with empty person type to Employee person type */
var gr = new GlideRecord("sys_user");
gr.setLimit(25);
gr.addEncodedQuery("active=true^u_oracle_idISNOTEMPTY^u_person_typeISEMPTY");
gr.query();
while(gr.next()) {
   gr.u_person_type = "Employee";
	gr.setWorkflow(false);
	gr.autoSysFields(false);
	gr.update();
	
}
gs.info("CJT Updated");



/*Loop all HR records
Find Record with matching category AND sub category values in u_hr_category_cleanup_lookup
IF changeRequired = empty DO NOTHING
ELSE
update
HR_Case.category = u_hr_category_cleanup_lookup.newCategory
HR_Case.Subcategory = u_hr_category_cleanup_lookup.newSubcategory
 */
var gr = new GlideRecord("hr_case");
//gr.setLimit(25);
gr.addQuery('number', 'HRC0415222');
gr.query();

//For each HR_Case record, find the corresponding lookup value, and update the HR_Case record to new mapped value in lookup
while(gr.next()){

	var lookup = new GlideRecord("u_hr_case_mapping");
	lookup.addQuery('u_category_old',gr.u_category);
	lookup.addQuery('u_subcategory_old',gr.u_subcategory);
	lookup.query();
	//gs.info("Test1");
	//Only 1 record will return.
	while(lookup.next()){
		gs.info(gr.number+' FROM ' + gr.u_category+' - ' + gr.u_subcategory+ ' TO ' + lookup.u_group_new +"."+lookup.u_category_new +"." +lookup.u_subcategory_new);
		gr.u_group_category = lookup.u_group_new;
		gr.u_category = lookup.u_category_new;
		gr.u_subcategory = lookup.u_subcategory_new;
		
		var classification = new GlideRecord('u_hr_classification');
		var strClassification = lookup.u_group_new +"."+lookup.u_category_new +"." +lookup.u_subcategory_new;
		classification.addQuery('u_full_name',strClassification);
		classification.query();
		while(classification.next()){
			gr.u_hr_classification_search = classification.sys_id;
		}
		
		gr.setWorkflow(false);
		gr.update();
	}
}


/* Cleanup V2 for u_group_categoryANYTHING^u_hr_classification_searchISEMPT */

var gr = new GlideRecord("hr_case");
//gr.setLimit(25);
gr.addEncodedQuery('u_group_categoryANYTHING^u_hr_classification_searchISEMPTY');
gr.addQuery('number', 'HRC0415222');
gr.query();

//For each HR_Case record, find the corresponding lookup value, and update the HR_Case record to new mapped value in lookup
while(gr.next()){
	
	gs.info(gr.number+' FROM ' + gr.u_category+' - ' + gr.u_subcategory+ ' TO ' + gr.u_group_category +"."+gr.u_category +"." +gr.u_subcategory);
	gr.u_group_category = lookup.u_group_new;
	gr.u_category = lookup.u_category_new;
	gr.u_subcategory = lookup.u_subcategory_new;
	
	var classification = new GlideRecord('u_hr_classification');
	var strClassification = gr.u_group_category +"."+gr.u_category +"." +gr.u_subcategory;
	classification.addQuery('u_full_name',strClassification);
	classification.query();
	while(classification.next()){
		gr.u_hr_classification_search = classification.sys_id;
	}
	
	gr.setWorkflow(false);
	gr.update();
	
}

/* Reporting Month Start population */
var gr=new GlideRecord("hr_case");
gr.addQuery('number', 'HRC0046756');
//gr.addQuery('u_reporting_month_start','=','');
gr.query();

while(gr.next()){
	var createdOn = new GlideDateTime(gr.getValue('sys_created_on'));
	createdOn = createdOn.getDate();
	gr.setValue('u_reporting_month_start', createdOn.getByFormat("YYYY-MM"));
	gr.setWorkflow(false);
	gr.update();
}

/* Reporting Month End population */
var gr=new GlideRecord("hr_case");
gr.addQuery('number', 'HRC0046679');
//gr.setLimit(25);
//gr.addQuery('u_reporting_month_end','=','');
gr.addQuery('closed_at','!=','');
gr.query();

while(gr.next()){
	var closedOn = new GlideDateTime(gr.getValue('closed_at'));
	closedOn = closedOn.getDate();
	gr.setValue('u_reporting_month_end', closedOn.getByFormat("YYYY-MM"));
	//var month = closedOn.getMonthNoTZ();
	//var year = closedOn.getYearNoTZ();
	//gr.setValue('u_reporting_month_end',year + "-" + month);
	gr.setWorkflow(false);
	gr.update();
}

/* Script to archive old knowledge base items into a new Knowledge base 
The following is the background script which can archive the old Knowledge items into a new knowledge base. 
Be careful with sys_ids, once you start this one, It will move all related records. */

var gr = new GlideRecord('kb_knowledge');
gr.setLimit(1);
gr.addEncodedQuery('kb_knowledge_base=e126baafdb78e300ccd1b29a689619dc');
//sys_id of HR Public (or any other suitable KB), which already contains records
gr.query();
while(gr.next()){
    gr.kb_knowledge_base = 'f900e650db612b008134b5ca689619ed';
    //sys_id of HR Archive (or any other new KB), which will store records
	 gr.setWorkflow(false);
	gr.update();
}
//the folowing is optional just to know how many records was moved 
//gs.print('Archived ' + gr.getRowCount() +' record(s)');

/* Script to change kb category 
The following is the script to change KB_category, otherwise categories will stay related to old knowledge base*/
var gr = new GlideRecord('kb_category');
//parent_id is knowledge base id (hr_public is this case)
gr.addEncodedQuery('parent_id=3c1a39680fde42004c9cfe6362050e4f');
gr.query();
while(gr.next()){
    //setting new parent_id (hr_archive in this case)
    gr.parent_id = 'e126baafdb78e300ccd1b29a689619dc';
    gr.update();
}


/* Script to set HR Classifications selectable name */
var gr = new GlideRecord("u_hr_classification");
gr.addQuery("u_has_child", false);
gr.query();
while (gr.next()) {
	gr.u_selectable_name = gr.u_name;
	gr.setWorkflow(false);
	gr.update();
}


javascript 截取屏幕截图并复制到剪贴板

截取屏幕截图并复制到剪贴板

screenshot_to_clipboard.js
jQuery(document).ready(function(){
    
    //активация первого пункта контета
    $('.w--tab-active .w-dyn-item:first-child a').addClass('active');
    
    $('.thumb-core a').attr("id", "target")
    
    let tab_link_attr = $('a[data-w-tab]').attr('data-w-tab');
    
    let link_first_block = $('div[data-w-tab="' + tab_link_attr + '"] .w-dyn-item:first-child a.active').attr("href");
            
    $('.thumb-core a').attr("href", "https://www.thomassantos.com" + link_first_block).css("background","transparent");
    
    let image_first_block = $('div[data-w-tab="' + tab_link_attr + '"] .w-dyn-item:first-child a.active img').attr("src");
    
    $('.thumb-core a').append("<img src='" + image_first_block + "'>").css({
        "border-radius": "5px",
        "overflow": "hidden"
    });
    
    
     $(".thumb-core a").on("click",function(e){
            e.preventDefault();
        });
    
    $('a[data-w-tab]').each(function(){
        
        $(this).on("click", function(){
           
            $('.w-tab-content a').each(function(){
               $(this).removeClass('active');
            });
             
            let tab_link_attr = $(this).attr('data-w-tab');
            
            $('div[data-w-tab="' + tab_link_attr + '"] .w-dyn-item:first-child a').addClass('active');
            
            
            let link_first_block = $('div[data-w-tab="' + tab_link_attr + '"] .w-dyn-item:first-child a.active').attr("href");
            
            $('.thumb-core a').attr("href", "https://www.thomassantos.com" + link_first_block).css("background","transparent");;
            
            let image_first_block = $('div[data-w-tab="' + tab_link_attr + '"] .w-dyn-item:first-child a.active img').attr("src");
            
            $('.thumb-core a').empty();
    
            $('.thumb-core a').append("<img class='img_content' src='" + image_first_block + "'>").css({
                "border-radius": "5px",
                "overflow": "hidden"
            });
        });
    });
    
    $("a.tab-card").each(function(){
        $(this).on("click", function(e){
            
            e.preventDefault();
             
            let current_link = $(this).attr("href");
            
            $('.thumb-core a').attr("href", "https://www.thomassantos.com" + current_link);
            
            let current_image_link = $(this).find("img").attr("src");
            
             $('.thumb-core a').empty();
            
             $('.thumb-core a').append("<img class='img_content' src='" + current_image_link + "'>").css({
                "border-radius": "5px",
                "overflow": "hidden"
            });
            
        });
    });
    
    
    //вешаем на кнопку цель
    $('.thumb-img-button').attr("data-clipboard-target", "#target").addClass('clipboard');
    
    $('.thumb-img-button div:first-child').on("click", function(){
        $(this).text("Done!");
        setTimeout(function(){
            $('.thumb-img-button div:first-child').text("Copy to clipboard");
        }, 2000);
    });
    
    
    var clipboard = new ClipboardJS('.clipboard');
                clipboard.on('success', function(e) {
                    console.log(e);
                });
                clipboard.on('error', function(e) {
                    console.log(e);
            });
    
});

javascript JS模块示例#2

module-example-2
// Example of module
// seed.js
export const seedData = [
  {
    id: 1,
    abbvTitle: 'Mon',
    fullTitle: 'Monday',
    events: [
      { details: 'Get Groceries', edit: false },
      { details: 'Carpool', edit: false }
    ],
    active: true
  },
  // ...,
}

// Using the module in another Vue file
// SomeComponent.vue
import { seedData } from './seed.js';

javascript 使用JS加载YouTube视频

只需将YouTube视频ID添加到“video-id”数据属性即可

HTML
<div class="youtube_video_lazy_load"
    data-video-id="AddYouTubeVideoIdHere"
    data-iframe-width="853"
    data-iframe-height="480"
    data-iframe-src-url-vars="rel=0&showinfo=0&&mute=1&disablekb=1">
</div>
JavaScript
var youtube_videos_loaded = 0;
        function loadYoutubeVideos() {
            $('.youtube_video_lazy_load').each(function () {

                if (youtube_videos_loaded == 0) {
                    var videoID = $(this).data("video-id");
                    var iframeWidth = $(this).data("iframe-width");
                    var iframeHeight = $(this).data("iframe-height");
                    var iframeSrcVars = $(this).data("iframe-src-url-vars");

                    if (videoID) {
                        var iframe = document.createElement("iframe");
                        iframe.setAttribute("frameborder", "0");
                        iframe.setAttribute("allowfullscreen", "");
                        iframe.setAttribute("src", "https://www.youtube.com/embed/" + videoID + "?" + iframeSrcVars);
                        iframe.setAttribute("width", iframeWidth);
                        iframe.setAttribute("height", iframeHeight);
                        /*iframe.setAttribute("allow", "accelerometer; encrypted - media; gyroscope; picture - in -picture");*/
                        $(this).html(iframe);
                    }

                }

            });

            youtube_videos_loaded = 1;
        }

    var lastScrollTop = 0;
    $(window).scroll(function (event) {
        var st = $(this).scrollTop();
        if (st > lastScrollTop) {
            loadYoutubeVideos();
        } else {
            // up scroll code
        }
        lastScrollTop = st;
    });

javascript Redux基本结构

Redux如何工作的基本实现

redux-basics.js
const redux = require('redux');
const createStore = redux.createStore;

const initialState = {
	counter: 0
}

//Reducer
const rootReducer = (state = initialState, action) => {
	if (action.type === 'INC_COUNTER') {
		return {
			...state,
			counter: state.counter + 1
		}
	}
	if (action.type === 'ADD_COUNTER') {
		return {
			...state,
			counter: state.counter + action.value
		}
	}
	return state;
}

//Store
const store = createStore(rootReducer);
console.log(store.getState());

//Subscription(calls function passed to it every time an action is beeing dispatched)
store.subscribe(() => {
	console.log('[Subscription]', store.getState());
})

//Dispatching Action
store.dispatch({type: 'INC_COUNTER'});
store.dispatch({type: 'ADD_COUNTER', value: 10});
console.log(store.getState());

reducer-example.js
import * as actionTypes from './actions';

const initialState = {
	counter: 0,
	results: []
}

const reducer = (state = initialState, action) => {
	switch (action.type) {
		case actionTypes.INCREMENT:
			return {
				...state,
				counter: state.counter + 1
			}
		case actionTypes.DECREMENT:
			return {
				...state,
				counter: state.counter - 1
			}
		case actionTypes.ADD:
			return {
				...state,
				counter: state.counter + action.val
			}
		case actionTypes.SUBTRACT:
			return {
				...state,
				counter: state.counter - action.val
			}
		case actionTypes.STORE_RESULT:
			return {
				...state,
				results: state.results.concat({id: new Date(), value: state.counter})
			}
		case actionTypes.DELETE_RESULT:
			// const id = 2;
			// const newArray = [...state.results];
			// newArray.splice(id, 1);
			const updatedArray = state.results.filter(result => result.id !== action.resultId)
			return {
				...state,
				results: updatedArray
			}
	}
	return state;
}

export default reducer;

javascript 空与未定义

script.js
// unndefined - Represents an absence of value. Assigned by the system. Should let unefined just happen.
// null - Represents an absence of valuee. Assigned by the prograam. If you are assigning an absence of value, use null

var a;
// example 1
if(!a){	a = 100;}

// example 2
if(a === 'undefined'){	a = 100;}

// example 3
if(typeof a === 'undefined'){a = 100;}
console.log(a); // 100

javascript UPS i-parcel JavaScript调试代码

i-parcel_debug
iparcel.settings.showWelcomeMat();