【问题标题】:function still applied after Modernizr test failedModernizr 测试失败后功能仍然适用
【发布时间】:2012-05-27 09:46:23
【问题描述】:

我正在使用 Modernizr 运行触摸事件测试,测试似乎运行良好,但仍然是我仅在测试成功时才调用的函数。

这是测试:

Cluster.prototype.test_touch_event_support = function(callback) {
    return (Modernizr.touch) ? callback : log("Touch Support Undetected");
};

这是只有在测试成功时才应该运行的函数:

Cluster.prototype.initiate_shop_touch_events = function() {
    var self = this;
    return $("#" + this.shop_wrapper_id).hammer({prevent_default: true, drag_min_distance: Math.round(this.viewport_width * 0.1)}).bind("drag", function(ev) {
        var data = JSON.parse(self.get_local_storage_data(self.shop_data_key));
        var step = (ev.direction == "left") ? 1 : -1;
        var new_page = parseInt(data.current_page + step);
        return (new_page > 0 && new_page <= data.total_pages) ? $(self.shop_navigation_class).jPages(new_page) : false;
});
};

我正在这样检查,即使它不依赖于我传递给测试的参数:

self.test_touch_event_support(self.initiate_shop_touch_events());

有人能告诉我为什么这个函数还在运行吗?因为我还在控制台中收到不支持触摸事件的消息。

【问题讨论】:

    标签: javascript touch modernizr


    【解决方案1】:
    self.test_touch_event_support(self.initiate_shop_touch_events());
    

    将调用 self.initiate_shop_touch_events的结果传递给self.test_touch_event_support

    你需要做的:

    self.test_touch_event_support(self.initiate_shop_touch_events);
    

    传递函数。

    在

    Cluster.prototype.test_touch_event_support = function(callback) {
        return (Modernizr.touch) ? callback : log("Touch Support Undetected");
    };
    

    您需要调用回调而不是引用它。

    Cluster.prototype.test_touch_event_support = function(callback) {
        return (Modernizr.touch) ? callback.call (this) : log("Touch Support Undetected");
    };
    

    经验教训:

    1. 了解调用函数和引用函数之间的区别。与许多编程语言不同,JavaScript 中的函数是一流的实体。您可以通过调用它们的名称来传递对它们的引用。要调用、调用或执行函数,您必须在函数引用之后立即指定一个用括号括起来的参数列表(可能为空)。
    2. 调用时,所有函数都会传递一个上下文参数,该参数在函数体中使用单词this 引用。这通常通过在函数名称前加上对象引用来指定,例如obj.func (123) 在此调用中,每次函数体引用 this 时都会使用对象 obj。使用这种用法,函数必须是对象的已定义方法。函数的call 和apply 方法可用于显式指定此上下文参数:当func 不是obj 的方法时,func.call (obj, 123) 等效于上述方法。

    更多细节可以在这里找到https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function

    【讨论】:

    • 即使参数是函数?
    • @Roland 是的,因为您需要将 reference 传递给函数,而不是函数的 result。
    • 我明白了,我刚刚进行了测试,似乎如果我启用了触摸事件,该函数将无法运行:) 也许是因为参数是引用而不是函数?
    • 我已经尝试过了,但收效甚微。你可以在这里查看:rolandgroza.com/projects/roland。用鼠标拖动,它应该根据您提供的解决方案工作(只需否定测试,这样您就可以使用鼠标拖动而不是触摸拖动)。
    • 因为您正在丢失上下文(this 变量的值)请参阅上面的更多编辑。
    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多