H. Mahida
H. Mahida

Reputation: 2366

How to create a 'chaining' JavaScript API with intermediate 'fluent' verbage?

I am creating js sdk, where I am looking for creating user (API)/ user call function like;

var user = new user();

user.message.to("username").get.friendlist(function(data){
    //process data received from callback.
});

Now, I know that method chaining can be done, and I am able to make something like

function User(Name) {
    this.uname = Name;
}

User.prototype = {
    constructor: User,

    MessageTo: function (username) {
        this.uname = username;
        return this;
    },

    getFriendList: function (callback) {
        callback("My list");
    }
}

and I can use it as below after creating object of User();

user.messageTo("username").getFriendList(function(data){
});

But I have no Idea about how to get the method call like what I am looking for as;

user.message.to("username").get.friendlist(function(data){
});

Evan I am not sure if it is possible or not. Any help or pointer with same regards is appreciated.

Upvotes: 3

Views: 325

Answers (1)

H. Mahida
H. Mahida

Reputation: 2366

As, commented by other member, there are other option to do same thing, but as I have to do it the way I needed here is how we managed to do that.

This solution fits in my requirement, so may be not best suited in other cases.

sdk.js

var User = function(){
UserName = null;
this.message = {

to : function(uname){

  UserName = uname   
  alert('called to '+uname);

  this.get = {
    friendlist : function(callback){
      console.log('called friendlist');
        callback('Hello friendlist :: '+ UserName);
    }
  }
  return this;
  }
  };
}

and using it like;

  var user1 = new User();

  user1.message.to('H.Mahida').get.friendlist(function(data){
      alert('call back says '+ data);
  });

Here is link to jsfiddle

Hope it may be useful to some one or guide in same direction...!!!

Upvotes: 1

Related Questions