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的更多相关文章

  1. jQuery来源学习笔记:扩展的实用功能

    // 扩展的实用功能 jQuery.extend({ // http://www.w3school.com.cn/jquery/core_noconflict.asp // 释放$的 jQuery 控 ...

  2. jQuery源码分析-03扩展工具函数jQuery.extend

    // 扩展工具函数 jQuery.extend({ // http://www.w3school.com.cn/jquery/core_noconflict.asp // 释放$的 jQuery 控制 ...

  3. 改善你的jQuery的25个步骤 千倍级效率提升

    1. 从Google Code加载jQueryGoogle Code上已经托管了多种JavaScript类库,从Google Code上加载jQuery比直接从你的服务器加载更有优势.它节省了你服务器 ...

  4. jQuery选择器引擎和Sizzle介绍

    一.前言 Sizzle原来是jQuery里面的选择器引擎,后来逐渐独立出来,成为一个独立的模块,可以自由地引入到其他类库中.我曾经将其作为YUI3里面的一个module,用起来畅通无阻,没有任何障碍. ...

  5. 从零开始学习jQuery (九) jQuery工具函数

    一.摘要 本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案,  即使你会使用jQuery也能在阅读中发现些许秘籍. 我们经常要使用脚本处理各种业务逻辑, 最常见的就 ...

  6. jquery遍历筛选数组的几种方法和遍历解析json对象

    jquery grep()筛选遍历数组 $().ready(    function(){        var array = [1,2,3,4,5,6,7,8,9];        var fil ...

  7. 改善你的jQuery的25个步骤

    1. 从Google Code加载jQueryGoogle Code上已经托管了多种JavaScript类库,从Google Code上加载jQuery比直接从你的服务器加载更有优势.它节省了你服务器 ...

  8. [转]JQuery - Sizzle选择器引擎原理分析

    原文: https://segmentfault.com/a/1190000003933990 ---------------------------------------------------- ...

  9. day63-webservice 09.jquery调用ajax

    WebService可以有很多种调用方式,除了之前说的,还可以有jquery.拿原生的Ajax做调用,拿jquery怎么调用啊?原生的能调,jquery指定也能调.原生的Ajax是通过网页直接点HTM ...

随机推荐

  1. c/c++与Python的语法差异

    1.程序块语法方面: c/c++中用一对“{}”将多段语句括起来,表示一个程序块,并以右大括号表明程序块结束 ;i<n;i++) { cout<<a[i]; j+=; } Pytho ...

  2. 【C语言】二维指针做形参

    转自:http://hi.baidu.com/gpmzccqceabimqq/item/f499f057aa1520404eff208b 关键: 传入时强制类型转换 + 使用时自己手工寻址 今天写程序 ...

  3. MVC3.0删除数据的时候给提示信息

    Index.cshtml代码: @model IEnumerable<FirstMvc.Models.Book> <script type="text/javascript ...

  4. 阿里云ecs Linux平台安装mongodb数据库

    MongoDB提供了linux平台上32位和64位的安装包,你可以在官网下载安装包. 下载地址:http://www.mongodb.org/downloads 下载完安装包,并解压 tgz(以下演示 ...

  5. HTTP长连接和短连接原理浅析

    原文出自:HTTP长连接和短连接原理浅析

  6. Swift - 状态栏颜色显示(字体、背景)

    ios上状态栏 就是指的最上面的20像素高的部分 状态栏分前后两部分,要分清这两个概念,后面会用到: 前景部分:就是指的显示电池.时间等部分: 背景部分:就是显示黑色或者图片的背景部分: 如下图:前景 ...

  7. find 查找文件 -exec 然后压缩 查看tar包的内容

    [root@cs Downloads]# find ./ -name "banner*" -exec tar -cvf k.tar "{}" \; ./bann ...

  8. EasyUi – 2.布局Layout + 3.登录界面

    1.页面布局 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.a ...

  9. Android N 新特性 + APP开发注意事项

    1. 多窗口MultiWindow 多窗口MultiWindow,这是Android N里对开发者影响比较大的特性,也是大家疑问比较多的地方.站在开发者的角度其实不必太担心这个特性会导致我们需要修改很 ...

  10. AngularJS——依赖注入

    依赖注入    依赖注入(DI)是一个经典的设计模式, 主要是用来处理组件如何获得依赖的问题.关于DI,推荐阅读Martin Flower的文章(http://martinfowler.com/art ...