How to chain JavaScript API with intermediate fluent word?

I am creating a js sdk where I am looking to create a custom (API) / custom 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 can do 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 like below after creating User () object;

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

      

But I have no idea how to invoke the method call like what I am looking for,

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

      

EVAN I'm not sure if this is possible or not. Any help or pointer with the same symptoms is appreciated.

+3


source to share


1 answer


As commented by another member, there is another possibility to do the same, but since I have to do it the way I need it here, this is how we managed to do it.

This solution meets my requirement, so it may not be better 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 a link to jsfiddle

Hope this can be helpful to someone or a guide in the same direction ... !!!

+1


source







All Articles