使用“类/对象"; jQuery中的MooTools风格的事件 [英] Using "class/object" MooTools-style events in jQuery

查看:108
本文介绍了使用“类/对象"; jQuery中的MooTools风格的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MooTools的优点之一是,它使您可以轻松地为对象分配/触发事件,例如:

One of the nice things about MooTools, is that it lets you easily assign/fire events to objects, for example:

var playerSingleton = new (new Class({
  Implements: [Events],

  initialize: function() {},

  setVolume: function() { 
    // do some stuff..
    this.fireEvent('volumeChanged')
  }

}));

// Somewhere else...

playerSingleton.addEvent('volumeChanged', function() {
  // do something when volume changes
});

playerSingleton.setVolume(75);
// bam our event fires.

如何用jQuery完成类似的事情? 我知道有.bind.trigger,但似乎唯一的方法是将事件绑定/触发到窗口对象:

How would something like this be done with jQuery? I know there's .bind and .trigger, but it seems like the only way to do this is to bind/fire events to the window object:

$(window).bind('volumeChanged', fn);

有什么比MooTools方法更好的了吗?谢谢!

Is there anything better than this, more like the MooTools approach? Thanks!

推荐答案

jQuery的绑定和触发器似乎适用于普通对象.尚未查看源代码以了解其工作原理(无论它是否是公共API的一部分),但确实如此.参见此讨论与去年相同想法.

jQuery's bind and trigger seem to work on normal objects. Haven't seen the source code to see how it works (if it's part of the public API or not), but it does. See this discussion from last year poking around the same idea.

player是一个常规对象,具有设置音量和添加侦听器以更改音量的方法. 此处的示例.

player is a regular object, with methods to set volume, and add listeners for volume change. an example here.

var player = {
    setVolume: function() {
        $(this).trigger("volumeChanged");
    },

    addVolumeChangeHandler: function(fn) {
        $(this).bind("volumeChanged", fn);
    }
};

// add a listener
player.addVolumeChangeHandler(function() {
    alert("volume has been changed");
});

// change volume (should fire the attached listener)
player.setVolume(); // alerts "volume has been changed"

这篇关于使用“类/对象"; jQuery中的MooTools风格的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆