本文介绍了普通Javascript对象上的jQuery.bind()事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将jQuery事件绑定到普通的非DOM Javascript对象是否可以:

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

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

$(myobject).trigger("foobar");

    $有什么影响b $ b
  • 垃圾收集(没有新的引用创建阻止对象到GC')

  • Garbage collection (no new references created preventing object to GC'ed)

对象属性(分配给对象的新属性) )?

Object attributes (new attributes assigned to the object)?

表现

有些事情我注意到了


  • 事件名称不得与对象上的函数名称冲突,例如你不能有函数init和事件名为init并触发它correclty

推荐答案

而不是使用jquery事件系统,我会实现一个使用方法来模仿它。 / p>

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"); 

但是,为了回答你的问题,我除了没有记录之外,没有看到你正在做什么的任何直接问题,并且可能会在版本之间改变功能(尽管它适用于所有当前可用的版本1.2.6 +)。

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+).

这篇关于普通Javascript对象上的jQuery.bind()事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 06:14