简体   繁体   English

跨JavaScript对象引用事件侦听器

[英]Reference an event listener across JavaScript objects

So I have written an API that would allow different applications to handle online/offline detection: 所以我编写了一个API,允许不同的应用程序处理在线/离线检测:

function onOffAPI() {

    var connection;

    function init() {
        var onLoadStatus = window.navigator.onLine;

        window.addEventListener('online', function() {
            connection.status = true;
        }, false);

        window.addEventListener('offline', function() {
            connection.status = false;
        }, false);

        return {
            status: onLoadStatus
        };
    }

    return {
        getStatus: function () {
            if (!connection) {
                connection = init();
            }
            return connection;
        }
    };
}

So a sample app uses the following code to detect whenever the application is online or offline: 因此,示例应用程序使用以下代码来检测应用程序何时在线或离线:

var $alert = $('.alert');
var notification = new onOffAPI();
var networkStatus = notification.getStatus().status;

$alert.text('Online: ' + notification.getStatus().status); //returns true if online, false if offline

Being able to reference the API when the application loads is straightforward, but I'm perplexed as how to reference the event listeners whenever the network connection were to suddenly change from online to offline, or vice versa. 能够在应用程序加载时引用API很简单,但是我困惑的是,每当网络连接突然从联机更改为脱机时,如何引用事件侦听器,反之亦然。 Could someone help me out here? 有人可以帮帮我吗?

I can see what you're trying to do, but I think you're going about it in the wrong way. 我可以看到你想要做什么,但我认为你是以错误的方式去做。 What you really want is to re-expose the online and offline events as a new 'connectionStatus' event. 您真正想要的是将在线和离线事件重新公开为新的“connectionStatus”事件。 What you currently have would require that you poll the api for the status, whereas you really want it to be event driven. 您目前拥有的将要求您轮询api以获取状态,而您确实希望它是事件驱动的。

It looks like you're using jQuery, so I hope you don't mind if I use jQuery in this example. 看起来你正在使用jQuery,所以我希望你不介意我在这个例子中使用jQuery。 The following has two methods for being notified of the status. 以下有两种方法可以通知状态。 One method is to use jQuery callbacks, the other is to expose a new event "connectionStatus": 一种方法是使用jQuery回调,另一种方法是公开一个新的事件“connectionStatus”:

var apiOnlineOffline = (function () {
    var callbacks = $.Callbacks('unique memory'),
        eventName = 'connectionStatus';

    function setStatus(status) {
        $(window).trigger(eventName, status);
        callbacks.fire(status);
    }

    function addCallback(callback) {
        callbacks.add(callback);
    }

    return {
        init: function () {
            // document.body #becauseIE8
            document.body.addEventListener('online', function () {
                setStatus(true);
            });
            document.body.addEventListener('offline', function () {
                setStatus(false);
            })

            // Set the initial status; assume true for browsers that don't support onLine property.
            setStatus(window.navigator.onLine || true)
        },

        addCallback: addCallback
    };
}());

Usage: 用法:

<p>
    Current connection status (event): <span id="statusEvent"></span>
</p>

<p>
    Current connection status (callback): <span id="statusCallback"></span>
</p>

<script type="text/javascript">
    $(function () {
        // Using events.
        $(window).on('connectionStatus', function (event, online) {
            $('#statusEvent').text(online.toString());
        });

        // Using callbacks.
        apiOnlineOffline.addCallback(function (online) {
            $('#statusCallback').text(online.toString());
        })

        // Note; this must appear last or the event version won't work.
        apiOnlineOffline.init();
    });
</script>

Hope this helps. 希望这可以帮助。

Reference: caniuse.com article for online-offline . 参考: caniuse.com在线离线文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM