Canjs Plugins Proxy

canjs
canjs-plugins

What is the purpose of the proxy plugin?

var Animal = can.Construct.extend({
    init: function(name) {
        this.name = name;
    },
    speak: function (words) {
        console.log(this.name + ' says: ' + words);
    }
});

var dog = new Animal("Gertrude");

// Passing a function
var dogDance = dog.proxy(function(dance){
    console.log(this.name + ' loves dancing the ' + dance);
});

dogDance('hokey pokey'); // Gertrude loves dancing the hokey pokey

In the above code, we define the Animal class as normal, and dog is just an instance of the Animal class. dog.proxy takes a function as an argument, and returns another function such that when invoked, the original function is invoked with dog bound to the this keyword.

What happens when we pass an array of functions to the proxy method?

Passing an array of functions returns a function that when executed will call the functions in order applying the returned values from the previous function onto the next function.

var dogCount = dog.proxy([
    function (start){
        console.log(start);
        return [start, start + 1];
    },
    function(start, next) {
        console.log(start + ' ' + next);
        return [start, next, next + 1];
    },
    function(start, next, last) {
        console.log(start + ' ' + next + ' ' + last);
    }
]);
dogCount(3); // 3, 3 4, 3 4 5

What happens if we pass a string as a parameter to the proxy method?

A string can be passed instead of a function and this will be used to look the function up on the constructor:

var Animal = can.Construct.extend({
    init: function(name) {
        this.name = name;
    },
    speak: function (words) {
        console.log(this.name + ' says: ' + words);
    }
});

var dog = new Animal("Gertrude");

var dogTalk = dog.proxy('speak');
dogTalk('This is crAAaaaaAAzzzyyy'); // Gertrude says: This is crAAaaaaAAzzzyyy

How many parameters can the proxy method accept?

Any number of arguments to be partially applied to the first function:

var func = function(feeling, thing){
    console.log(this.name + ' ' + feeling + ' ' + thing);
};

// Passing one argument (partial application)
var dogLoves = dog.proxy(func, 'loves');
dogLoves('cupcakes!'); // Gertrude loves cupcakes!

// Passing many arguments
var dogHateUnicorns = dog.proxy(func, 'hates', 'unicorns');
dogHateUnicorns(); // Gertrude hates unicorns

If you pass more than one parameter to proxy, the additional parameters will be passed as parameters to the callback before any parameters passed to the proxied function.

If you pass an array of functions and strings as the first parameter to proxy, proxy will call the callbacks in sequence, passing the return value of each as a parameter to the next.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License