Using Jquery (or even just Javascript), how to chain commands together - javascript

There are several functions in jquery which you can do the following:
$('#element').each().get('title').othercmd()
How can I create a class ( or a series of classes ) to replicate this behavior?
Basically, I want to something like this:
test = new Something()
test.generateSection('title').addData('somedata')
What is correct for this?
Thanks

One approach is to return "this" (the object) in each function. So you could do something like this:
<script>
var Something = function() {
this.hi = function() {
alert('hi');
return this;
};
this.bye = function() {
alert('bye');
return this;
};
}
var myObj = new Something();
myObj.hi().bye();
</script>

Just return the thing that you are operating on at the end of each method. (this usually).

You can implement a chain pattern just by returning the current instance in all the methods that you want to be able to chain.
Something.prototype.generateSection = function(title){
... code ...
this.sectionAdded = ...;
return this;
}
Something.prototype.addData = function(data)
{
... continue manipulating this.sectionAdded however you need it ..
return this;
}
And do the same with the other methods of your "class". Something to keep in mind is that you must store the objects that you will need in future calls, in your case you are generating a section, so you would have to put that inside your instance (in some private variable like sectionAdded) so you will be able to continue manipulating it from other methods.

I don't know if there is a way to easily chain together commands with plain javascript, but if you wanna try this with jQuery, you'll have to write your code as a jQuery plugin.
It's actually pretty easy and there are tons of tutorials for writing your own plugins.
One of the easiest I came across is this tutorial:
building-your-first-jquery-plugin-that.html

Related

extending existing method

So, I have a lot of places with code, when I push some elements to array:
arr.push(...)
But the problem is, that I would like to run custom code after each push. Basically the question is not only about this example. What I want to do is something like this:
func1.func2(...);
After this I want to run another function which will get all things, which func2 did and for example log it. But these functions in code are a lot and it is not desirable to write something like this every time:
if (func1.func2(...)) {
log_results();
}
Instead, for every func1.func2() I want automatically run another separate function, which will get results and log it.
The only way to really accomplish this is to wrap it in a function that does the extra work you want.
function pushAndLog(item) {
arr.push(item);
// Additional Code here
logResults();
}
This is an interesting question. There are plenty of libraries like Lodash that do similar things to functions. Like methods that return copies of functions with arguments partially applied: _.curry. I tested it and it works on Array.prototype.push.
Doing some research I found this post with this answer: JavaScript: clone a function and decided to try to do what you wanted without making the clone method.
Here is what I came up with. Replace the console.log with a call to any function you like or any other code you wish.
Array.prototype.push = (function() {
var old = Array.prototype.push;
var push = function () {
console.log('my new push where I can do what I want, like log some stuff');
return old.apply(this, arguments)
};
return push;
})();
var foo = [];
foo.push(1,2,3);
console.log(foo);
You could add another prototype to Array that uses push inside and then whatever else you want to execute.
let testArr = [];
Array.prototype.pushPlusStuff = function(val) {
this.push(val);
console.log("executing other stuff here");
};
testArr.pushPlusStuff("test");
console.log(testArr);
This will make the .pushPlusStuff method available to all Arrays
Actually gforce301 code helped me. I was dealing with Google dataLayer and the task was to log all push data (except some). This code snippet helped me:
var dataLayer_copy = dataLayer.push;
dataLayer.push = function() {
dataLayer_copy.apply(this, arguments);
console.log(JSON.stringify(arguments));
$.post('/log', {data: arguments}, function() {
}, 'json');
};

BackboneJS - using keyword this inside view

If i want to call a function inside Backbone view, i have to call it like this.
this.functionName()
If i want to call the same function inside forEach Or jquery's each function, this refers to different context here. So i need to hold view's reference to some other variable and i have to use it something like below.
refresh: function () {
var view = this;
$("#list").each (function () {
view.functionName();
})
}
And finally, if i look at my view, i declare like this almost all of my functions. Did anyone find better alternative for this?
Since you are using Backbone, you would already have underscore. Using underscore you can specify context for each call.
refresh: function() {
_.each($("#list"), function() {
this.functionName()
}, this))
}
This is indeed common in Javascript, by convention they call the variable that:
var that = this
jQuery also has a proxy() function which will call a function and set the context variable (this) to something you assign: http://api.jquery.com/jQuery.proxy/
So you could do something like this:
refresh: function() {
$("#list").each($.proxy(function() {
view.functionName()
}, this))
}
But most of the times it is even more unreadable. To be honest I never use proxy() and I can't think of a good example of when to use it, but it's nice to know of it's existance, might you ever need it.
The usuals are defining either var that = this; or var self = this; or var _this = this;
The Airbnb JavaScript Style Guide which I find very sane advocates the latter. (you may want to scroll a little to find the meat).

How can I create a selector like how jQuery has jQuery() or $()?

I have been creating my own library for a custom layout script. For ease of use, I am trying to emulate how jQuery exposes its library through the jQuery() which makes the code very easy to read and straightforward. I have come up with something that works but I am not sure if this is the correct way to do this. Rather than keep the functions internal all the functions are "appended" to the library. Anyways, the code which works for me so far is as follows:
slateUI = (function(slateID){
slateUI.ID = slateID;
return slateUI;
});
and a related function looks something like this:
slateUI.doSomething = function(content)
{
//DID SOMETHING USING slateUI.ID
}
I am fairly new to OOP like features of the language. I am sure there is a better way to approach this. The issue that I have is handing down the Element to an appened function call so for instance:
slateUI("#someSlate").doSomething(...)
Obtains its element from the slateUI.ID
Is this the correct way to approach this? Or is this a hacked way that I came up with and there is some straight forward way to do this?
// function which returns a new SlateUI object (so we dont have to use the "new" keyword)
slateUI = function ( slateID ) {
return new SlateUI( slateID );
};
// class definition
function SlateUI ( slateId ) {
this.id = slateId;
}
// methods added to the class prototype (allows for prototypical inheritance)
SlateUI.prototype.someFunction = function() {
alert( this.id );
return this; // adding this line to the end of each method allows for method chaining
};
// usage
slateUI( 'someid' ).someFunction();
The short version of your question is that you're looking for the ability to chain your functions.
This is achieved simply by returning the relevant object from each function. If the function has no other return value, then just return the this variable, to pass control back to the caller.

jQuery plugin design pattern (common practice?) for dealing with private functions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I've been developing jQuery plugins for quite some time now, and I like to think I know how to design one well by now. One issue keeps nagging me though, and that is how to deal with private functions in a powerful yet elegant manner.
My plugins generally look something like this:
(function($) {
$.fn.myplugin = function(...) {
...
// some shared functionality, for example:
this.css('background-color', 'green');
...
};
$.fn.mypluginAnotherPublicMethod = function(...) {
...
// some shared functionality, for example:
this.css('background-color', 'red');
...
};
}(jQuery));
Now my question is: how to neatly DRY up that shared functionality? An obvious solution would be to put it in a function within the plugin's namespace:
var fill = function($obj, color) {
$obj.css('background-color', color);
};
Although this solution is effective and nicely namespaced, I really dislike it. For one simple reason: I have to pass it the jQuery object. I.e. I have to call it like this: fill(this, 'red');, while I would like to call it like this: this.fill('red');
Of course we could achieve this result by simply putting fill into jQuery.fn. But that feels very uncomfortable. Imagine having ten plugins developed based on this approach and each plugin putting five of those 'private' functions into the jQuery function namespace. It ends up in a big mess. We could mitigate by prefixing each of these functions with the name of the plugin they belong to, but that doesn't really make it more attractive. These functions are supposed to be private to the plugin, so we do not want to expose them to the outside world at all (at least not directly).
So there's my question: does anyone of you have suggestions for how to get the best of both worlds. That is; plugin code being able to call 'private' plugin functions in a way similar to this.fill('red') (or this.myplugin.fill('red') or even this.myplugin().fill('red') etc.), while preventing jQuery function namespace pollution. And of course it should be light-weight, as these private functions might be called very frequently.
UPDATE: Thanks for your suggestions.
I especially like David's idea of defining an object type that holds the 'private' functions and wraps a jQuery object. The only problem with it is that it still disallows me from chaining 'private' and 'public' functions. Which was big reason to want a syntax like this.fill('red') to begin with.
I ended up with a solution which I consider not tremendously elegant, but appealing to the 'best of both worlds' cause:
$.fn.chain = function(func) {
return func.apply(this, Array.prototype.slice.call(arguments, 1));
};
Which allows for constructs like:
this.
find('.acertainclass').
chain(fill, 'red').
click(function() {
alert("I'm red");
});
I cross-posted my question in other places, which also collected some interesting responses:
http://forum.jquery.com/topic/jquery-plugin-design-pattern-common-practice-for-dealing-with-private-functions
http://groups.google.com/group/jquery-en/browse_thread/thread/fa8ccef21ccc589a
One thing first: if you would like to call something like this.fill('red'); where this is an instance of jQuery, you have to extend the jQuery prototype and make fill() "public". jQuery provides guidelines for extending it's prototype using so called "plugins" that can be added using $.fn.fill, which is the same as jQuery.prototype.fill.
In jQuery callbacks, this is often a reference to the HTML Element, and you can't add prototypes to those (yet). That is one of the reason why jQuery wraps elements and return jQuery instances that can be easily extended.
Using the (function(){})(); syntax, you can create and execute "private" javascript on the fly, and it all disappears when it's done. Using this technique, you can create your own jQuery-like syntax that wraps jQuery into your own private chainable object.
(function(){
var P = function(elem) {
return new Private(elem);
};
var Private = function(elem) {
this.elem = jQuery(elem);
}
Private.prototype = {
elem: null,
fill: function(col) {
this.elem.css('background',col);
return this;
},
color: function(col) {
this.elem.css('color', col);
return this;
}
}
$.fn.myplugin = function() {
P(this).fill('red');
};
$.fn.myotherplugin = function() {
P(this).fill('yellow').color('green');
};
})();
$('.foo').myplugin();
$('.bar').myotherplugin();
console.log(typeof P === 'undefined') // should print 'true'
This way, the P stands for your own toolbox of "private" functions. They won't be available anywhere else in the code or in the jQuery namespace unless you attach them somewhere. You can add as many methods as you like in the Private object, and as long as you return this, you can also chain them jQuery-style as I did in the example.
How about (within the plugin's scope):
var fill = function ()
{
(function (color)
{
this.css ('backgrorund-color', color);
//.. your stuff here ...
}).apply (this, arguments);
}
$.fn.myplugin = function ()
{
fill ('green');
}
That way, fill will retain the jQuery context you're in, and is still private to your plugin
Amended: the above is incorrect w.r.t. scoping, Try the following instead:
var fill = function (color)
{
if (!$this) return; // break if not within correct context
$this.css ('backgrorund-color', color);
//.. your stuff here ...
}
$.fn.myplugin = function ()
{
var $this = $(this); // local ref to current context
fill ('green');
}
You might want to take a look at how the jQuery UI Widget Factory is implemented.
The basic approach is like this:
(function($){
$.fn.myplugin = function(method)
{
if (mp[method]) // map $('foo').myplugin('bar', 'baz') to mp.bar('baz')
{
return mp[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || ! method)
{
return mp.init.apply(this, arguments); // if called without arguments, init
}
else
{
$.error('Method ' + method + ' does not exist on $.myplugin');
}
};
// private methods, internally accessible via this.foo, this.bar
var foo = function() { … };
var bar = function() { … };
var private = { // alternative approach to private methods, accessible via this.private.foo
foo : function() { … },
bar : function() { … }
}
var mp = { // public methods, externally accessible via $.myplugin('foo', 'bar')
init : function( options )
{
return this.each(function()
{
// do init stuff
}
},
foo : function() { … },
bar : function() { … }
};
})(jQuery);
Unfortunately, "private" methods (or any property for that matter) can never be called with a "this" prefix in javascript. Anything which is called like this.myFunc(myArgs) must be publicly available.
And "private" methods can only be called from within the scope in which they were defined.
Your original solution is the only one that will work. Yes, it's a pain having to pass in this, but there's no more verbosity than there would be if your impossible request was possible:
this.fill('green');
//or
fill(this,'green');
As you can see, they both take up exactly the same number of characters in your code.
Sorry to say, but you're stuck with this as a solution, unless you want to create a new namespace and make them not private - which is simply going to add to the amount of code you need to write, i.e. what you indirectly called "not directly exposed":
this.myplugin.fill('green');
...is more verbose, thus kind of defeats the purpose.
Javascript is not like other languages, there are no "private" members per-se, only members accessible within closures, which can sometimes be used in a similar way to private members, but is more of a "workaround", and not the "real-deal" private members you are looking for.
It can be difficult to come to terms with this (I often struggle), but don't try to mould javascript into what you understand from other languages, take it for what it is...

Lazy Load External Javascript Files

I am trying to write a javascript class that loads script files as they are needed. I have most of this working. It is possible to use the library with the following Syntax:
var scriptResource = new ScriptResource('location/of/my/script.js');
scriptResource.call('methodName', arg1, arg2);
I would like to add some additional syntactic sugar so you could write
var scriptResource = new ScriptResource('location/of/my/script.js');
scriptResource.methodName(arg1, arg2);
I'm almost certain that this isnt possible but there may be an inventive solution. I guess what there need to be is some sort of methodCall event. SO the following could work
ScriptResource = function(scriptLocation)
{
this.onMethodCall = function(methodName)
{
this.call(arguments);
}
}
This code is obviously very incomplete but I hope it gives an idea of what I am trying to do
Is something like this even remotely possible?
There is a non standard method, __noSuchMethod__ in Firefox that does what you're looking for
have a look at
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/noSuchMethod
so you could define
obj.__noSuchMethod__ = function( id, args ) {
this[id].apply( this, args );
}
If the set of method names is limited, then you could generate those methods:
var methods = ["foo", "bar", "baz"];
for (var i=0; i<methods.length; i++) {
var method_name = methods[i];
WildCardMethodHandler[method_name] = function () {
this.handleAllMethods(method_name);
};
}
edit: Posted this answer before the question changed dramatically.
An intermediary solution might be to have syntax such as:
var extObj = ScriptResource('location/of/my/script.js');
extObj('methodname')(arg1,arg2);
the code might look like this:
function ScriptResource(file) {
return function(method) {
loadExternalScript(file);
return window[method];
}
}
All kinds of assumptions in the code above, which I'd let you figure out yourself. The most interesting, IMHO, is - in your original implementation - how do you get the proxyied method to run synchronously and return a value? AFAIK you can only load external scripts asynchronously and handle them with an "onload" callback.

Categories