stick-to-this

0.0.3 • Public • Published

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.

Why use it?

Bluebird's .bind method makes it possible for multiple steps in a promise chain to collaborate on context, where they utilize resources from the context object. For example:

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

Unfortunately, this will break a 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 t = new Transform('hello ', '!');
   var context {message: 'george'};
   return Promise.bind(context)
       .then(t.prepend)    //breaks: this.prefix will not be there
       .then(t.append)     //breaks: this.suffix will not be there

If somehow both context and t 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.

Package Sidebar

Install

npm i stick-to-this

Weekly Downloads

1

Version

0.0.3

License

MIT

Last publish

Collaborators

  • michael-wynn