更改现有活动的参考

时间:2016-07-20 13:59:30

标签: javascript jquery

我有以下JavaScript代码:

var MyGlobalRef = (function () {

    function init(obj1, obj2) {

        prepareEvents(obj1);
        prepareEvents(obj2);

        function prepareEvents(obj) {

            var handleMouseUp = function (evt) {
                // do work with obj
            };

            obj.addEventListener('mouseup', handleMouseUp);
        }
    }
    return {
        init: init
    }
})();

在我的主页中,我经常调用init函数,如下所示:

function moveNext(){
    MyGlobalRef.init(getNewObj1(), getNewObj2());
}

我的问题是,在moveNext()函数上,我倾向于替换现有对象,这意味着页面中始终只有2个对象。但是,我调用moveNext越多,生成的事件侦听器就越多。因此,当我moveNext 3次时,鼠标向上事件每个鼠标向上发射3次。显而易见的解决方案是仅在第一次调用addEventListener。但是,这个问题是obj(在鼠标向上事件中使用)不会更新并仍然引用原始obj。另外,我没有使用removeEventListener,因为我一旦启动就没有对obj的引用。

2 个答案:

答案 0 :(得分:2)

扩展我的评论。这就是我想象的。由于destroy执行

,您返回init函数

解决方案#1

var MyGlobalRef = (function () {

    function init(obj1, obj2) {

        prepareEvents(obj1);
        prepareEvents(obj2);

        function prepareEvents(obj) {

            var handleMouseUp = function (evt) {
                // do work with obj
            };

            obj.addEventListener('mouseup', handleMouseUp);
        }

        return function() {
          obj1.removeEventListener('mouseup');
          obj2.removeEventListener('mouseup');
        };
    }
    return {
        init: init
    }
})();


// cleanup is a variable stored in your code to run a cleanup on obj1 and obj2 later on

function moveNext(){
    if (cleanup) {
      cleanup();
    }

    cleanup = MyGlobalRef.init(GetNewObj1A(), GetNewObj1A());
}

解决方案#2 在关闭时继续引用obj1obj2

var MyGlobalRef = (function () {

    var _obj1;
    var _obj2;

    function init(obj1, obj2) {

        prepareEvents(obj1);
        prepareEvents(obj2);

        function prepareEvents(obj) {

            var handleMouseUp = function (evt) {
                // do work with obj
            };

            obj.addEventListener('mouseup', handleMouseUp);
        }

        _obj1 = obj1;
        _obj2 = obj2;
    }
    function cleanup() {
        if (_obj1) {
          _obj1.removeEventListener('mouseup');
        }

        if (_obj2) {
          _obj2.removeEventListener('mouseup');
        }
    }
    return {
        init: init,
        cleanup: cleanup
    }
})();



function moveNext(){
    MyGlobalRef.cleanup();
    MyGlobalRef.init(GetNewObj1A(), GetNewObj1A());
}

答案 1 :(得分:-1)

在函数之前调用prepareEvents,在init函数之前放置函数prepareEvents(obj)。试试吧。