Documentation

BX.proxy/BX.delegate

Function 
BX.proxy(
 Function func,
 Object context
);
Function 
BX.delegate(
 Function func,
 Object context
);

Two related functions, generating a "function-delegate", which will be calling a required function in a required context. It can be used, for example, for assigning method of a object as an event handler with preservation of objects' context.

The difference between functions is that when BX.proxy is called repeatedly with the same parameters, It will return not the new delegate function, but the link to the function, generated previously. Which can be useful, for example, if a specific event handler must be cancelled.

Note: BX.delegate - similar to jQuery.proxy.

Examples of use

Code to get an element, which was clicked:

_hadleMoreButtonClickHandler: function(e)
{
   alert(BX.proxy_context.innerHTML);
}

BX.bind(BX('test'), 'click', BX.delegate(this._hadleMoreButtonClickHandler, this));
<script type="text/javascript">
function MyClass()
{
    this.prop = 1;
    BX.bind(BX('link'), 'click', BX.proxy(this.handler, this));
}

MyClass.prototype.handler = function()
{
    alert(this.prop);
    BX.unbind(BX('link'), 'click', BX.proxy(this.handler, this));
}

BX.ready(function(){ new MyClass(); });
</script>
<a href="javascript:void(0)" id="link">Click Me</a>
function MyClass(){}
MyClass.prototype.handler = function(){}

var ob = new MyClass();
alert(BX.delegate(ob.handler, ob) == BX.delegate(ob.handler, ob)); // false
alert(BX.proxy(ob.handler, ob) == BX.proxy(ob.handler, ob)); // true

A more practical example, demonstrating the passing of execution context when delegating. As an example, an anonymous function is called in the following context:

My.prototype.test = function(d)
{
    console.log(d);
};
My.prototype.send = function()
{
    BX.ajax.get(this._ajaxPage, post, function(data){
        this.test(data);
    });
};

Also, reasonably standard situation is when after the ajax-requset we are performing some actions with the data. However, if when executing the provided code, the this.test(data); string results in an error (because, in this context, this will refer to the anonymous function itself). To preserve code transparency, its sufficient to wrap the anonymous function call into the BX.delegate:

My.prototype.test = function(d)
{
    console.log(d);
};
My.prototype.send = function()
{
    BX.ajax.get(this._ajaxPage, post, BX.delegate(function(data){
        this.test(data);
    }, this));
};

This time, the string this.test(data) will be called without error and will invoke a method of your class: My.



© «Bitrix24», 2001-2022
Up