Creating libraries with multiple runs like Jquery

Asked

Viewed 99 times

2

I am now starting to develop my own Javascript libraries. I already understand a little how the prototype but I still don’t understand how I can perform in the same request more of a method just like jquery does... EX:

//no jquery eu posso executar qualquer função em cascata assim
$('alguma coisa').metodo1().metodo2().metodo3();

//ou assim
$('alguma coisa').metodo1();
$('alguma coisa').metodo2();
$('alguma coisa').metodo3();

I would like to know how I can create a simple library that I can run numerous methods at the same time as Jquery does...

1 answer

3


Just at the end of the method you return the object itself (Return this) :

Example:

var Numero = function(num){
 this.num = num;
 this.valueOf = function(){
    return this.num;
 }
 this.maisUm = function(){
    this.num += 1;
    return this;
  }
  this.maisDois = function(){
    this.num += 2;
    return this;
  }
  return this;
}
var meuNum = new Numero(1);
alert(meuNum.maisUm().maisDois().maisUm() + 1); //1 + 1 + 2 + 1 + 1 = 6

Javascript is a very flexible language, when I use Numero = function(num){ ... } I am creating a class Number and indicating that function(num){...} is your constructor method. Within this method, I can use the properties of this to define class properties and methods.

  • but if I do that I’m bound to always return the record in one, and if I have more than one structured element in this it breaks me...

  • 1

    Otherwise, javascript has a magic method called valueOf, that allows an object to behave as a primary value. Example: var numDuplo = Function(num){ this.num = num * 2; this.valueOf = Function(){ Return this.num}}

  • 1

    @Leandroluk And you can also use without "new" to look more like jQuery. Example: Number(3). moreUm(). moreUm() + 1 //returns 6

  • what I’m really looking for is to generate a library that I can cross methods... getting more into the subject I’m creating a library to work on the window.localStorage almost as if it were SQL itself and because of the SQL variants I need to be able to inject numerous elements when necessary...

  • The way I exemplified it gives you a good north of how to do that. Let’s say you want to fetch a data from localStorage that is like json and take a specific property from it, you could create a library that behaves as follows: localStorageLib('seuItemNoLocalStorage'). get(). parseJson().propertyQueVoceQuer.val()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.