jQuery.bind() events on plain Javascript objects

前端 未结 2 1915
感动是毒
感动是毒 2021-02-05 11:50

Is it ok to bind jQuery events to plain, non-DOM Javascript objects:

var myobject = {};
$(myobject).bind(\"foobar\", function() { alert(\"daa\"); });

$(myobject         


        
2条回答
  •  滥情空心
    2021-02-05 12:32

    Instead of using the jquery event system, I would implement one that mimics it using the jQuery.Callbacks method.

    var myClass = function(){
        this._callbacks = {};
    };
    myClass.prototype = {
      addEvent: function(evname,callback) {
        if (!this._callbacks[evname]) {
          this._callbacks[evname] = $.Callbacks();
        }
        this._callbacks[evname].add(callback);
      },
      removeEvent: function(evname) {
        if (!this._callbacks[evname]) {
          return;
        }
        this._callbacks[evname].remove();
        //Might need this too:
        //this._callbacks[evname] = null;
      },
      triggerEvent: function(evname) {
        if (this._callbacks[evname]) {
          this._callbacks[evname].fire();
        }
      }
    };
    var foo = new myClass();
    foo.addEvent("foo",function(){
      console.log('foo');
    });
    foo.triggerEvent("foo");
    foo.removeEvent("foo");
    // event was removed, the below line won't do anything.
    foo.triggerEvent("foo"); 
    

    http://jsfiddle.net/kEuAP/


    However, to answer your question, I don't see any immediate problems with what you are doing other than it isn't documented and may change functionality from version to version (although it works in all currently available versions 1.2.6+).

提交回复
热议问题