Search code examples
javascriptcallbind

Binding an argument as this, with a new constructor?


I am trying to bind an argument for this to a function named Sequence the binding works, problem is more than one Sequence overwrites each other, so I have to use new here's the issue...

//js code
function init(cmd) {
    cmd.exec.call(e,Sequence.bind(cmd));
}

Example

init({
    exec:function(seq){
        seq("a",function(){
            console.log(this);// returns init object itself
        });
    }
});

Works great but when I do

//init for js above
...,function(seq) {
    seq("a",function(){
        console.log ("hello");
    },document.getElementById("google"));
});
...,function(seq) {
    seq("d",function(){
        console.log("goodbye");
    });
});

The second sequence is ran goodbye. never the first because it is being written over.

Sequence function

function Sequence(key, fn, location) {
    if (!location) location = document;
    var self = this; //object that is bound to Sequence
    location.addEventListener("keydown", function sequenceMode(e) {
      if(self.waiting)
      {
        if (keyCodes.literal[key.toUpperCase()] === e.which) {
          fn.call(self,e);
          self.waiting = false;
          this.removeEventListener("keydown", sequenceMode);
        }
      } else location.removeEventListener("keydown", sequenceMode);
    });
}

So my issue here is how do I A bind the this property to be the object calling Sequence or B how do I create a new instance of Sequence and still allow the user to define inside the function?

cmd.call(e,new Sequence().bind(cmd)); //can not call bind from Constructor

So basically I need to have the user still be able to define the arguments themselves for Sequence and this be bound to the object calling it. Any suggestions?

EDIT

http://jsbin.com/dulesejame

Not getting the same results so I'm overlooking my code now, So I've edited the bin with my actual JavaScript. It's doing it now.

Open the developer panel to read console. Press ctrl+a then b, then press ctrl+b press a, doesn't show any so press b and it's running ctrl+a seq function.


Solution

  • One main issue I can tell you is using the same default object, by which your commands.cmd[combinator] will point to the same object which came last.

    Make a copy of default before assigning

    var def = Object.create(defaults);
    for(var option in options)
    {
      if(option !== "executed" && option !== "called")
      {
        def[option] = options[option];
      }
    }