2011-01-07 20 views
1

在我的Javascript和Flex应用程序中,用户经常执行的操作是我希望页面上的其他Javascript代码进行侦听。例如,如果有人添加了一个朋友。我想要我的Javascript应用程序然后调用像triggerEvent("addedFriend", name);。然后,任何其他正在监听“addedFriend”事件的代码都将与该名称一起被调用。使用Javascript和jQuery进行听力和射击活动

是否有内置的Javascript机制来处理事件?我也可以使用jQuery,我知道jQuery广泛使用事件。但是对于jQuery来说,它的事件机制似乎都是基于元素的。据我所知,你必须将自定义事件绑定到一个元素。我想我可以做到这一点的虚拟元素,但我的需要与网页上的DOM元素无关。

我应该自己实现这个事件机制吗?

回答

3

您有几种选择:

  • jQuery的确实允许您使用不与文档相关的对象做到这一点。下面提供了一个例子。
  • 如果你还没有在你的页面上使用jQuery,那么添加它可能是矫枉过正。还有为此设计的其他库。您提到的模式称为PubSub发布/订阅
  • 正如您所建议的那样,您自己实现它,因为如果您仅查看基本功能,这并不困难。

jQuery的例子:

var a = {}; 
jQuery(a).bind("change", function() { 
    alert("I changed!"); 
}); 
jQuery(a).trigger("change"); 
+0

当然,如果你有JQuery的,无论如何,我相信你会找到其他地方,你会发现它*很有用。您还可以获得使用在无数开发人员的生产环境中经过测试和测试的代码的好处,而您自己的实现可能会遇到一些错误。此外,计算机变得越来越快,所以与@ Box9例子中更快实现的几行代码相比,实现自己的几毫秒页面载入的好处并不是那么好。 – jmort253 2011-01-07 01:28:21

0

我会实现这样的使用MVVM模式与knockjs库。

0

只需创建一个元素,并在其上使用jQuery事件。 它可能只是一个全局变量,甚至不必连接到DOM。 通过这种方式,您可以轻松完成任务,而无需任何额外的库。

0

除了单击事件之外,是不是可以绑定onchange事件?例如,如果调用addFriend并修改页面上的列表,则可以绑定change事件,然后调用其他功能。

$('#addFriendButton').click(function() { 
     // modify the #friendList list 
    }); 



    $('#friendList').change(function() { 
     myOtherAction(); 
    }); 
0

这是总主机独立的,不需要的jQuery或DOM在这种情况下!

function CustomEvents(){ 
//object holding eventhandlers 
this.handlers_ = {}; 
} 
//check if the event type does not exist, create it. 
//then push new callback in array. 
CustomEvents.prototype.addEventListner = function (type, callBack){ 
if (!this.handlers_[type]) this.handlers_[type] = []; 
    this.handlers_[type].push(callBack); 
} 

CustomEvents.prototype.triggerEvent = function (type){ 
//trigger all handlers attached to events 
if (!this.handlers_[type]) return; 
for (var i=0, handler; handler = this.handlers_[type][i]; i++) 
{ 
    //call handler function and supply all the original arguments of this function 
    //minus the first argument which is the type of the event itself 
    if (typeof handler === "function") handler.apply(this,arguments.slice(1)); 
} 

} 
//delete all handlers to an event 
CustomEvents.prototype.purgeEventType = function(type){ 
return delete this.handlers_[type]; 
} 

测试:

var customEvents = new CustomEvents(); 
customEvents.addEventListner("event A", function(arg){alert('Event A with arguments' + arg);)); 
customEvents.triggerEvent("event A", "the args"); 

编辑添加参数传递