Eyem Gdi
Eyem Gdi

Reputation: 13

How to chain in Javascript without Jquery?

When i search for answers for JS chaining, i get something like this which is j-query.

$("#wrapper").fadeOut().html("Welcome, Sir").fadeIn();

i want to know if there is any chaining method not related to j-query. please.

Upvotes: 1

Views: 480

Answers (4)

Joseph
Joseph

Reputation: 119867

Chaining is possible because each method in jQuery returns a jQuery object. The initial call (the $()) creates a jQuery object. The rest are methods of jQuery that return a jQuery object. You can return the same instance or create a new one. In jQuery's case, they create new objects.

Here's a simple example of an object whose methods return itself.

function CustomObject(){
  if(!(this instanceof CustomObject)) return new CustomObject();
}

CustomObject.prototype.aMethod = function(){
  // do something
  return this;
}

CustomObject.prototype.anotherMethod = function(){
  // do something else
  return this;
}

// Use like
var a = CustomObject()
var b = a.aMethod().anotherMethod().anotherMethod();
a === b

Upvotes: 2

Abhisek Malakar
Abhisek Malakar

Reputation: 899

Chaining is not a magic,if the returned element is or subset of the initial object set then only chaining is applied. Thus you can't use $("#wrapper").fadeOut().html().fadeIn();

because when you use this .html() version m then the returned element is not an jquery object so the chain breaks. It is same for javascript.

Upvotes: 0

Beri
Beri

Reputation: 11620

Yes there is. t is simple chain of responsibility design pattern. Link to example: http://www.dofactory.com/javascript/chain-of-responsibility-design-pattern

In a nutshell your methods must return this (ref to current object)

Upvotes: 0

Kirill Pisarev
Kirill Pisarev

Reputation: 843

You can organize chaining by returning context in methods, f.e.

var chaining = {
    do: function(){
        // code here...
        return this;
    },
    stuff: function(){
        // and here...
        return this;
    }
}
chaining.do().stuff()

Upvotes: 4

Related Questions