1

我想扩展 $.mobile.changePage 以接受更多选项,例如在页面完成加载时添加回调函数,以及为 AJAX 调用(如 contentType)添加更多选项。有没有办法在不更改源代码的情况下做到这一点?如果没有,我愿意为教育目的更改源代码,但在 jQuery Mobile GitHub 中找不到它:https ://github.com/jquery/jquery-mobile 。感谢您提供任何帮助或指导。

4

1 回答 1

2

JavaScript 更令人兴奋的部分之一是能够使用通常称为Monkey Patching的技术重新定义任何函数。(顺便说一句,ES5 提供了一种新的freeze方法,允许开发人员防止此类修改。)

这是一个 JavaScript MonkeyPatch 的示例,它允许我们修改函数的行为而无需编辑它的源代码:

// A namespace object.
var Example = {};

// Sums two values.
Example.sum = function (a, b) {
    return a + b;
}

// Usage:
var result = Example.sum(1, 2);

假设我们想在 sum 方法中添加日志记录,我们可以console.log在函数中添加一行,但我们也可以对其进行修补:

// Store a reference to the current 'Example.sum' function.
var originalSum = Example.sum;

// Now redeclare Example.sum...
Example.sum = function (a, b) { 

    // Call the originalSum function first...
    var result = originalSum(a, b);

    // Now add some logging...
    console.log("Example.sum(" + a + ", " + b + ") yields " + result);

    return result;
};

现在当Example.sum被调用时,我们不仅会像以前一样得到结果,而且还会写入一个控制台消息。$.mobile.changePage考虑到这一点,您可以用同样的方式对方法进行修补:

var originalChangePage = $.mobile.changePage;

// Redefine `changePage` so it accepts a 'complete' function in the options
// object which will be invoked when the page change is complete.
$.mobile.changePage = function (to, options) {
    if (typeof options.complete === "function") {
        $(body).one("pagechange", function (event) { 
            options.complete(event);
        });
    }

    originalChangePage(to, options);
};
于 2012-08-15T13:47:34.010 回答