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. 开源一个基于nio的java网络程序

    因为最近要从公司离职,害怕用nio写的网络程序没有人能看懂(或许是因为写的不好吧),就调整成了mina(这样大家接触起来非常方便,即使没有socket基础,用起来也不难),所以之前基于nio写的网络程 ...

  2. 构建之法 第6~7章读后感和对Scrum的理解

    第六章-敏捷流程 第六章主要详细介绍了敏捷流程,在软件工程范畴里,“敏捷流程”是一系列价值观和方法论的集合.这一章以敏捷流程的Scrum方法论而展开,而敏捷流程的精髓就是在于快速的交付. 敏捷开发的流 ...

  3. 图片轮播(淡入淡出)--JS原生和jQuery实现

    图片轮播(淡入淡出)--js原生和jquery实现 图片轮播有很多种方式,这里采用其中的 淡入淡出形式 js原生和jQuery都可以实现,jquery因为封装了很多用法,所以用起来就简单许多,转换成j ...

  4. sql server索引功能资料

    无论何时对基础数据执行插入.更新或删除操作,SQL Server 数据库引擎都会自动维护索引.随着时间的推移,这些修改可能会导致索引中的信息分散在数据库中(含有碎片).当索引包含的页中的逻辑排序(基于 ...

  5. DotNetCore跨平台~性能测试~可以放心使用了

    使用dotnetCore发布站点后,它的处理请求能力不逊色IIS等大型服务的能力,号称每秒能处理115万个请求,太牛X了也. 先看看它支持的数据库 以下主流数据库都是为支持的 Microsoft SQ ...

  6. asp.net mvc 4 json大数据异常 提示JSON字符长度超出限制的异常

    今天客户突然过来找我说在后台添加了一篇超长的文章后,所有后台的文章都显示不出来了.后台的前端显示是用easyui的,返回的数据全是用json.根据客户的描述进行了同样的操作后,在firebug下发现a ...

  7. 重新想象 Windows 8 Store Apps (64) - 后台任务: 开发一个简单的后台任务

    [源码下载] 重新想象 Windows 8 Store Apps (64) - 后台任务: 开发一个简单的后台任务 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 后 ...

  8. ActiveReports 报表应用教程 (7)---交叉报表及数据透视图实现方案

    在 ActiveReports 中可以通过矩阵控件非常方便的实现交叉报表,同时还可以设置数据的分组.排序.过滤.小计.合计等操作,可以满足您报表的智能数据分析等需求.在矩阵控件中组的行数和列数由每个行 ...

  9. wrong requestcode when using startActivityForResult

    You are calling startActivityForResult() from your Fragment. When you do this, the requestCode is ch ...

  10. 环境搭建二 secureCRT配置

    上一篇里面讲到了虚拟机安装,以及secureCRT的远程连接.此篇文章介绍secureCRT的配置. 颜色设置 参考   http://jingyan.baidu.com/article/a681b0 ...