将空对象传递给jQuery函数 [英] Passing an empty object into jQuery function

查看:57
本文介绍了将空对象传递给jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当阅读Ben Alman的Pub/Sub库时,我在第一行就感到困惑,因为他将一个空对象传递给jQuery函数.此外,他使用绑定函数对象只是将其应用到几乎空"的对象中(我使用firebug来检查该对象,并且它只返回内部包含空对象的jQuery对象).有人可以为我解释这种逻辑吗? 非常感谢! P/S:我了解在非框架上下文中Pub/Sub模式的用法和思想,只是不了解在jQuery中的实现.

When reading Pub/Sub library by Ben Alman, I got confused at the very first line that he passed an empty object into jQuery function. Also, he uses bind function object just to apply it in that nearly "empty" object (I used firebug to examine that object and it just return an jQuery object contain empty object inside). Could someone explain this logic for me? Thank sooo much! P/S: I understand the usage and the idea behind Pub/Sub pattern in non-framework context, just don't understand its implementation in jQuery.

这是我已阅读的库代码:

Here is the code of library I've read:

 (function($){
    var o = $({});
    $.subscribe = function() {
        o.bind.apply( o, arguments );
    };
    $.unsubscribe = function() {
        o.unbind.apply( o, arguments );
    };
    $.publish = function() {
        o.trigger.apply( o, arguments );
    };
 })(jQuery);

推荐答案

创建一个元素的jQuery对象...最终对象包括所有jQuery方法

WHen you create a jQuery object of an element... final object includes all the jQuery methods

在简化示例中:

{ element: 'div'
    jQuery:{
      hide:function(){},
      animate:function(){}
       on:function(){}
    }

}

演示代码中的空对象用于执行相同的操作.一旦将其包装在$()中,它就可以绑定jQuery事件处理程序,因为该对象包括许多jQuery方法(并非全部)作为属性

The empty object in the demo code is used to be able to do the same thing. Once it is wrapped in $() it can have jQuery event handlers bound to it as the object includes many of the jQuery methods( not all) as properties

您可以这样写:

o.on('myCustomeEvent',doSomething);

在另一部分代码中

o.trigger('myCustomeEvent');

这篇关于将空对象传递给jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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