0.0.3 • Published 9 years ago

stick-to-this v0.0.3

Weekly downloads
2
License
MIT
Repository
github
Last release
9 years ago

What is it?

Creates a proxy function (from a an object's member function) with access to the parent object's data not otherwise available to it because the original this binding was lost or overridden when called. For example, that happens when the function is called in a bluebird promise chain and is preceded by a .bind instruction.

Status

Experimental

Why use it?

Bluebird's .bind method makes it possible for multiple steps in a promise chain to collaborate on a common context, where they utilize resources from the same context object without having to pass values or using wrapper functions. For example:

    var context = {/*...*/}
    return Promise.bind(context)
        .then(fn1)
        .then(fn2)
        .then(fn2);

Unfortunately, this will break if the function is a member of an object that depends on access to its original this. The below will not work:

   class Transform {
       constructor(_prefix, _suffix){
           this.prefix = _prefix;
           this.suffix = _suffix;
           }
       
       prepend(){
           this.message = this.prefix + this.message;
       }
           
       append(context){
           this.message += this.suffix;
       }
   }
   
   var transformer = new Transform('hello ', '!');
   var context {message: 'george'};
   return Promise.bind(context)
       .then(transformer.prepend)    //breaks: this.prefix will not be there
       .then(transformer.append)     //breaks: this.suffix will not be there

If somehow both context and transformer are available inside then the plan will work, and bind-to-this helps make that happen:

      
   var stick = require('stick-to-this');
   
   prepend(context){
       this.message = _this.prefix + this.message;
   }
   
   append(context){
       this.message += _this.suffix;
   }

   class Transform {
       constructor(_prefix, _suffix){
           this.prefix = _prefix;
           this.suffix = _suffix;
           this.prepend = stick(this, prepend);
           this.append = stick(this, append);
   }
   
   var t = new Transform('hello ', '!');
   var context {message: 'george'};
   return Promise.bind(context)
       .then(t.prepend)
       .then(t.append)

In a for useful setting, the context object may be a container that provides access to request and response objects.