no-jquery 05 Utilities
Utilities
type
// is this a function?
typeof someValue === 'function';
// is this an object?
someValue != null &&
Object.prototype.toString.call(someValue) === "[object Object]";
// works in modern browsers
Array.isArray(someValue);
// works in all browsers
Object.prototype.toString.call(someValue) === "[object Array]";
Combine and copy objects
// our helper function
function extend(first, second) {
for (var secondProp in second) {
var secondVal = second[secondProp];
// Is this value an object? If so, iterate over its properties, copying them over
if (secondVal && Object.prototype.toString.call(secondVal) === "[object Object]") {
first[secondProp] = first[secondProp] || {};
extend(first[secondProp], secondVal);
}
else {
first[secondProp] = secondVal;
}
}
return first;
};
// example use - updates o1 with the content of o2
extend(o1, o2);
// example use - creates a new object that is the aggregate of o1 & o2
var newObj = extend(extend({}, o1), o2);
Iterate over object properties
for (var myObjectProp in myObject) {
// deal with each property in the `myObject` object...
}
// works in all browsers
for (var prop in myObject) {
if (myObject.hasOwnProperty(prop)) {
// deal w/ each property that belongs only to `myObject`...
}
}
// works in modern browsers
Object.keys(myObject).forEach(function(prop) {
// deal with each property that belongs to `myObject`...
});
Iterate over array elements
// works in all browsers
for (var index = 0; i < myArray.length; i++) {
var arrayVal = myrray[index];
// handle each array item...
}
// works in modern browsers
myArray.forEach(function(arrayVal, arrayIndex) {
// handle each array item
}
Find an element in an array
// works in modern browsers
var indexOfValue = theArray.indexOf('c');
// works in all browsers
function indexOf(array, valToFind) {
var foundIndex = -1;
for (var index = 0; index < array.length; i++) {
if (theArray[index] === valToFind) {
foundIndex = index;
break;
}
}
}
// example use
indexOf(theArray, 'c');
// works in modern browsers
var allElementsThatMatch = theArray.filter(function(theArrayValue) {
return theArrayValue !== 'b';
});
// works in all browsers
function filter(array, conditionFunction) {
var validValues = [];
for (var index = 0; index < array.length; i++) {
if (conditionFunction(theArray[index])) {
validValues.push(theArray[index]);
}
}
}
// use example
var allElementsThatMatch = filter(theArray, function(arrayVal) {
return arrayVal !== 'b';
})
Turn a pseudo-array into a real array
var realArray = [].slice.call(pseudoArray);
[].forEach.call(pseudoArray, function(arrayValue) {
// handle each element in the pseudo-array...
});
Modify a function
Change a function's context
// works in modern browsers
function Outer() {
var eventHandler = function(event) {
this.foo = 'buzz';
}.bind(this);
this.foo = 'bar';
// attach `eventHandler`...
}
var outer = new Outer();
// event is fired, triggering `eventHandler`
// works in all browsers
function Outer() {
var self = this,
eventHandler = function(event) {
self.foo = 'buzz';
};
this.foo = 'bar';
// attach `eventHandler`...
}
var outer = new Outer();
// event is fired, triggering `eventHandler`
Create a new function with some pre-determined arguments
function log(appId, level, message) {
// send message to central server
}
var ourLog = log.bind(null, 'master-shake');
// example use
ourLog('error', 'dancing is forbidden!');
Trim a string
// works in modern browsers
' hi there! '.trim();
// works in all browsers, but needed in IE 8 and older
' hi there! '.replace(/^\s+|\s+$/g, '');
// works in all browsers
function trim(string) {
if (string.trim) {
return string.trim();
}
return string.replace(/^\s+|\s+$/g, '');
}
Associate data with an HTML element
// works in all browsers
var data = (function() {
var lastId = 0,
store = {};
return {
set: function(element, info) {
var id;
if (element.myCustomDataTag === undefined) {
id = lastId++;
element.myCustomDataTag = id;
}
store[id] = info;
},
get: function(element) {
return store[element.myCustomDataTag];
}
};
}());
// use it
// make the elements aware of each other
var one = document.getElementById('one'),
two = document.getElementById('two'),
toggle = function(element) {
if (element.style.display !== 'none') {
element.style.display = 'none';
}
else {
element.style.display = 'block';
}
};
data.set(one, {partnerElement: two});
data.set(two, {partnerElement: one});
// on click, either hide or show the partner element
// remember to use `attachEvent` in IE 8 and older, if support is required
one.addEventListener('click', function() {
toggle(data.get(one).partnerElement);
});
two.addEventListener('click', function() {
toggle(data.get(two).partnerElement);
});
// works only in the latest browsers
// make the elements aware of each other
var weakMap = new WeakMap(),
one = document.getElementById('one'),
two = document.getElementById('two'),
toggle = function(element) {
if (element.style.display !== 'none') {
element.style.display = 'none';
}
else {
element.style.display = 'block';
}
};
weakMap.set(one, {partnerElement: two});
weakMap.set(two, {partnerElement: one});
// on click, either hide or show the partner element
// remember to use `attachEvent` in IE 8 and older, if support is required
one.addEventListener('click', function() {
toggle(weakMap.get(one).partnerElement);
});
two.addEventListener('click', function() {
toggle(weakMap.get(two).partnerElement);
});
// works in all browsers
var data = window.WeakMap ? new WeakMap() : (function() {
var lastId = 0,
store = {};
return {
set: function(element, info) {
var id;
if (element.myCustomDataTag === undefined) {
id = lastId++;
element.myCustomDataTag = id;
}
store[id] = info;
},
get: function(element) {
return store[element.myCustomDataTag];
}
};
}());
no-jquery 05 Utilities的更多相关文章
- jQuery来源学习笔记:扩展的实用功能
// 扩展的实用功能 jQuery.extend({ // http://www.w3school.com.cn/jquery/core_noconflict.asp // 释放$的 jQuery 控 ...
- jQuery源码分析-03扩展工具函数jQuery.extend
// 扩展工具函数 jQuery.extend({ // http://www.w3school.com.cn/jquery/core_noconflict.asp // 释放$的 jQuery 控制 ...
- 改善你的jQuery的25个步骤 千倍级效率提升
1. 从Google Code加载jQueryGoogle Code上已经托管了多种JavaScript类库,从Google Code上加载jQuery比直接从你的服务器加载更有优势.它节省了你服务器 ...
- jQuery选择器引擎和Sizzle介绍
一.前言 Sizzle原来是jQuery里面的选择器引擎,后来逐渐独立出来,成为一个独立的模块,可以自由地引入到其他类库中.我曾经将其作为YUI3里面的一个module,用起来畅通无阻,没有任何障碍. ...
- 从零开始学习jQuery (九) jQuery工具函数
一.摘要 本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案, 即使你会使用jQuery也能在阅读中发现些许秘籍. 我们经常要使用脚本处理各种业务逻辑, 最常见的就 ...
- jquery遍历筛选数组的几种方法和遍历解析json对象
jquery grep()筛选遍历数组 $().ready( function(){ var array = [1,2,3,4,5,6,7,8,9]; var fil ...
- 改善你的jQuery的25个步骤
1. 从Google Code加载jQueryGoogle Code上已经托管了多种JavaScript类库,从Google Code上加载jQuery比直接从你的服务器加载更有优势.它节省了你服务器 ...
- [转]JQuery - Sizzle选择器引擎原理分析
原文: https://segmentfault.com/a/1190000003933990 ---------------------------------------------------- ...
- day63-webservice 09.jquery调用ajax
WebService可以有很多种调用方式,除了之前说的,还可以有jquery.拿原生的Ajax做调用,拿jquery怎么调用啊?原生的能调,jquery指定也能调.原生的Ajax是通过网页直接点HTM ...
随机推荐
- LeetCode 441 Arranging Coins
Problem: You have a total of n coins that you want to form in a staircase shape, where every k-th ro ...
- 让ar执行queryall和queryrow方法返回数组
让ar执行queryall和queryrow方法返回数组 <?phpnamespace common\components;use \CActiveRecord;use \Yii;use \CD ...
- 执行HQL语句出现Remember that ordinal parameters are 1-based
今天使用hibernate出个奇怪的错误,第一次碰到 Remember that ordinal parameters are 1-based! 原因是 问题发生的原因是:hql语句里不需要参数,却添 ...
- 416. Partition Equal Subset Sum
题目: Given a non-empty array containing only positive integers, find if the array can be partitioned ...
- 在web.xml中classpath和classpath*的区别
classpath 和 classpath* 区别: classpath:只会到你指定的class路径中查找找文件; classpath*:不仅包含class路径,还包括jar文件中(class路径) ...
- xth的旅行(codevs 1450)
题目描述 Description 毕业了,Xth很高兴,因为他要和他的 rabbit 去双人旅行了.他们来到了水城威尼斯.众所周知(⊙﹏⊙b汗),这里的水路交通很发达,所以 xth 和 rabbit ...
- python基础——错误处理
python基础——错误处理 在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因.在操作系统提供的调用中,返回错误码非常常见.比如打开文件的函数 ...
- 忘记Mysql登录密码
1,使用安全模式跳过验证: 如果 Mysql在运行,Kill掉. 如果mysqld_safe无法启动,可用管理员权限sudo . 2,本地登录: 启动Mysql 3,修改密码: 5.7之后, 更改密码 ...
- 利用CocoaPods,在项目中导入AFNetworking类库
场景1:利用CocoaPods,在项目中导入AFNetworking类库 AFNetworking类库在GitHub地址是:https://github.com/AFNetworking/AFNetw ...
- DB2 bind on z/os
BIND and REBIND options for packages and plans There are several options you can use for binding or ...