How to bind anonymous function in jQuery?

I am trying to bind an anonymous function in jQuery, but it does not work. I get the error message "Error: XML filter is applied to a value other than XML ...". What is the correct syntax or is there an effect function that I can use that does nothing visually and that wraps my function?

My example: $item.appendTo($list).(function() {.....}());

+8
jquery
source share
3 answers

Chains work by returning the original jQuery object as a result of calling this binder function. Hypothetically, to bind your anonymous functions, you must β€œreturn” the original jQuery object.

However, your function must be called from the context of the jQuery object. For example, there is a function

 $item.appendTo 

However, for the jQuery object, there is no function available for:

 $item.(function(){ }) 

Think of it this way. Let's say you have the following object:

 var obj = { foo: function(){ console.log(1); } }; 

The declaration of 'foo' is available as a property / declaration on obj. But what exactly does the declaration that you refer to the anonymous function mean?

 obj.(function(){ }) 

The only way to give your anonymous function the execution context of the jQuery object is to make a "call" on it

 (function(){ }).call($item, args); 

If you wanted to relate this, theoretically you could do this:

 (function(){ return this; }).call($item, args).appendTo($other); 

But I'm not sure what you get. Best to do this:

 $item.appendTo($list); (function($obj){ })($item); 

Or if you start with a selector:

 var $item = $('#someID').appendTo($list); (function($obj){ })($item); 

Although, at the moment, anonymous functions are not so useful, so I just:

 var someFunc = function($obj){ }; $item.appendTo($list); someFunc($item); 
+7
source share

you can use the .each method

 $item.appendTo($list).each( function() {.....} ); 

Alternatively, you can extend the jquery object with your own functions ( jQuery.fn.extend() ).

 $.fn.extend({ myOwnFunc: function(){ /*do whatever*/ return this; // to allow for further chaining. } }); 

and now you can call $item.appendTo($list).myOwnFunc()

+5
source share

Must not be:

 $item.appendTo($list).(function() {.....})(); 

I completely forgot to mention the return of $;

0
source share

Source: https://habr.com/ru/post/649963/


All Articles