Jquery plugin method returns value not object

I wrote a jq plugin where first I want to initialize the selected elements (all of them are each). Later in the code I want to get the line created by the method. But all it returns are objects, but not my string.

I have done a lot of research on the Internet, but I don’t know how to make the plugin “dockable” on the one hand, and “return any values” on the other hand.

what do you think?

(function($){ var methods = { init: function(val){ // Actions to initialize ALL selected Elements } , returner: function(val){ alert('working with every selected element: '+$(this).width()); // return anything return 'STRING PRODUCED BY THIS FUNCTION!'; } } $.fn.myplug = function(method){ var args = arguments; var init = 'init-myplug'; return this.each(function(){ var is_init = $(this).data(init); if (is_init && methods[method]){ return methods[method].apply($(this), Array.prototype.slice.call(args, 1)); } else if (!is_init && (typeof method === 'object' || !method)){ $(this).data(init, true); return methods.init.apply($(this), Array.prototype.slice.call(args, 0)); } }); }; })(jQuery); $('.selects_5_elements').myplug(); // init $('.selects_5_elements').myplug('returner'); // get the string 
+4
source share
2 answers

The first step is to collect the results of your method. At the moment, you are trying to return the result of the method through each callback that will not work (the return value in each callback is used to exit the loop).

I would suggest collecting all the results in such an array:

 var results = []; this.each(function(){ var is_init = $(this).data(init); if (is_init && methods[method]){ results.push(methods[method].apply($(this), Array.prototype.slice.call(args, 1))); } else if (!is_init && (typeof method === 'object' || !method)){ $(this).data(init, true); results.push(methods.init.apply($(this), Array.prototype.slice.call(args, 0))); } }); 

At this point, you can simply return an array of results. But if you want some methods to be chained, while others return the results of a method call, then you will need to check the method name to decide which value will be returned.

 if (method == 'returner') return results; else return this; 

Also note that we are returning an array here, not a string. The reason is because your method will be called for each element matching the selector. Therefore, if you have five matching elements, you will get an array of 5 lines.

If you really want to return only one row, you need to decide how to handle all duplicates. Do you want to combine all the lines? Or return only the first row? Or just the last line? All options are easy enough to do - what you choose will depend on your requirements.

+2
source

The only thing you need to do is put it in an EACH callback:

 if ( args.length === 0 ) { // Init your plugin return this; } if ( args[0] === "returner" ) { // Generate your string return "STRING PRODUCED BY THIS FUNCTION!"; } 
0
source

All Articles