function writeCode(callback) {

    // do something...

    callback();

    // ...

}

function introduceBugs() {

    // ... make bugs

}

writeCode(introduceBugs); 

A Callback Example

// refactored findNodes() to accept a callback

var findNodes = function (callback) {

    var i = 100000,

          nodes = [],

          found;

    // check if callback is callable

    if (typeof callback !== "function") {

        callback = false;

    }

    while (i) {

        i -= 1;

        // complex logic here...

        // now callback:

        if (callback) {

            callback(found);

        }

        nodes.push(found);

    }

    return nodes;

};

Callbacks and Scope

var myapp = {};

myapp.color = "green";

myapp.paint = function (node) {

    node.style.color = this.color;

};

The function findNodes() does something like this:

var findNodes = function (callback) {

    // ...

    if (typeof callback === "function") {

         callback(found);

    }

    // ...

};

If you call findNodes(myapp.paint), it won’t work as expected, because this.color will not be defined. The object this will refer to the global object, because findNodes() is a global function. If  findNodes() were a  method  of  an  object  called  dom (like dom.findNodes()), then this inside of the callback would refer to dom instead of the expected myapp.

pass the callback function and in addition pass the object this callback belongs to

findNodes(myapp.paint, myapp);

var findNodes = function (callback, callback_obj) {

    //...

    if (typeof callback === "function") {

        callback.call(callback_obj, found);

    }

    // ...

};

pass the method as a string

findNodes("paint", myapp);

var findNodes = function (callback, callback_obj) {

    if (typeof callback === "string") {

        callback = callback_obj[callback];

    }

    //...

    if (typeof callback === "function") {

        callback.call(callback_obj, found);

    }

    // ...

};

Asynchronous Event Listeners

document.addEventListener("click", console.log, false);

Timeouts

var thePlotThickens = function () {

    console.log('500ms later...');

};

setTimeout(thePlotThickens, 500);

Callbacks in Libraries

Focus on core functionality and provide “hooks” in the form of callbacks, which will allow the library methods to be easily built upon, extended, and customized.

JavaScript Patterns 4.2 Callback Pattern的更多相关文章

  1. JavaScript Patterns 5.5 Sandbox Pattern

    Drawbacks of the namespacing pattern • Reliance on a single global variable to be the application’s ...

  2. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

  3. JavaScript Patterns 5.4 Module Pattern

    MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...

  4. JavaScript Patterns 5.1 Namespace Pattern

    global namespace object // global object var MYAPP = {}; // constructors MYAPP.Parent = function() { ...

  5. JavaScript Patterns 2.6 switch Pattern

    Principle • Aligning each case with switch(an exception to the curly braces indentation rule). • Ind ...

  6. JavaScript:回调模式(Callback Pattern) (转载)

    JavaScript:回调模式(Callback Pattern) 函数就是对象,所以他们可以作为一个参数传递给其它函数: 当你将introduceBugs()作为一个参数传递给writeCode() ...

  7. JavaScript Patterns 4.8 Function Properties - A Memoization Pattern

    Gets a length property containing the number of arguments the function expects: function func(a, b, ...

  8. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  9. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

随机推荐

  1. Direct3D11学习:(三)Direct3D11初始化

    转载请注明出处:http://www.cnblogs.com/Ray1024 一.概述 做完一系列的准备工作之后,我们就正式进入Direct3D11的学习了.我们就从Direct3D11的初始化工作开 ...

  2. Firefox中一个很好用的host工具--HostAdmin

    支持分组的功能超级好用 host中如下添加 [#] 17 [# COMMENT]#==== 17#192.168.0.17 www.xxx.com#192.168.0.17 1.xxx.com#192 ...

  3. 五分钟,运用cocoaui库,搭建主流iOS app中我的界面

    本项目基于天天团购项目,在上一篇中有说到! 首先介绍一些cocoaui,是国内的一名程序员做的开源的开源系统,目的是为了简化ios布局!官网地址:www.cocoaui.com,github地址:ht ...

  4. 计算几何 : 凸包学习笔记 --- Graham 扫描法

    凸包 (只针对二维平面内的凸包) 一.定义 简单的说,在一个二维平面内有n个点的集合S,现在要你选择一个点集C,C中的点构成一个凸多边形G,使得S集合的所有点要么在G内,要么在G上,并且保证这个凸多边 ...

  5. [CLR via C#]14. 字符、字符串和文本处理

    一.字符 在.NET Framewole中,字符总是表示成16位Unicode代码值,这简化了国际化应用程序的开发. 每个字符都表示成System.Char结构(一个值类型) 的一个实例.System ...

  6. c# dynamic动态类型和匿名类

    dynamic类型 简单示例 dynamic expando = new System.Dynamic.ExpandoObject(); //动态类型字段 可读可写 expando.Id = 1; e ...

  7. js获取url传递的参数

    获取URL带参数的JAVASCRIPT客户端解决方案 一.正则分析法.(我较喜欢使用正则)function GetQueryString(name) {var reg = new RegExp(“(^ ...

  8. Python记录-Pip安装

    1.第一步 下载py文件:https://bootstrap.pypa.io/ez_setup.py #!/usr/bin/env python """ Setuptoo ...

  9. 【C#进阶系列】10 属性

    属性分为无参属性和有参属性(即索引器). 属性相对于字段的优点不仅仅是为了封装,还可以在读写的时候做一些额外操作,缓存某些值或者推迟创建一些内部对象,也适用于以线程安全的方式访问字段. 话说最基本的属 ...

  10. EventUtil 根据IE自动适配事件

    var EventUtil = { addHandler: function (element, type, handler) { if (element.addEventListener) { el ...