Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrapping plain javascript object in jquery $({})

I have this fragment of code from a book I am reading. And want to understand what $({}) means and what is its use exactly.

I tried searching on several search engines and even on SO. $({}) wasn't a search-friendly term.

    var Events = {
       bind: function(){
          if ( !this.o ) this.o = $({});
          this.o.bind.apply(this.o, arguments);
       },

       trigger: function(){
          if ( !this.o ) this.o = $({});
          this.o.trigger.apply(this.o, arguments);
       }
    };

I did find a similar question about $([]) but I don't think it is quite the same thing.

like image 863
Arturo Hernandez Avatar asked Sep 06 '12 16:09

Arturo Hernandez


1 Answers

You're just wrapping a basic javascript object as a jQuery one.

From jquery documentation :

Working With Plain Objects

At present, the only operations supported on plain JavaScript objects wrapped in jQuery are: .data(),.prop(),.bind(), .unbind(), .trigger() and .triggerHandler(). The use of .data() (or any method requiring .data()) on a plain object will result in a new property on the object called jQuery{randomNumber} (eg. jQuery123456789).

// define a plain object
var foo = {foo:'bar', hello:'world'};

// wrap this with jQuery
var $foo = $(foo);

// test accessing property values
var test1 = $foo.prop('foo'); // bar

// test setting property values
$foo.prop('foo', 'foobar');
var test2 = $foo.prop('foo'); // foobar

// test using .data() as summarized above
$foo.data('keyName', 'someValue'); console.log($foo); // will now contain a
                                                      // jQuery{randomNumber}
                                                      // property

// test binding an event name and triggering
$foo.bind('eventName', function (){
    console.log('eventName was called');
});

$foo.trigger('eventName'); // logs 'eventName was called'

Should .trigger('eventName') be used, it will search for an 'eventName' property on the object and attempt to execute it after any attached jQuery handlers are executed. It does not check whether the property is a function or not. To avoid this behavior, .triggerHandler('eventName') should be used instead.

$foo.triggerHandler('eventName'); // also logs 'eventName was called'

Here's a (not really useful) example :

​var a =$({});
a.data('b', 3);
console.log(a.data('b')); // this prints 3

If you keep your object created with $({}), you may use it as callee for data, bind, and so on. This is probably the minimal non DOM keepable jquery object you can make.

like image 124
Denys Séguret Avatar answered Sep 22 '22 16:09

Denys Séguret