Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegating a function call in Javascript

Is there a way in Javascript to have a delegate like the ones in c# ?

Example in c#

Object.onFunctionCall = delegate (vars v) {
    Console.WriteLine("I can do something in this private delegate function");
};

I would like with my Javascript to have my main object do something over a long time, and shot a delegate once in a while to give a little update. All that without having to change the code itself of my class to adjust for the webpage.

function mainObject() {
    this.onUpdate = function() { //Potentially the delegate function here
    }
}

var a = new mainObject();
a.onUpdate = Delegate {
      $(".myText").text("Just got a delegate update");
} 

I dunno if it's clear enough.. havent found ressources on this so I suppose there is just no way to do so ?

NOTE: I am not looking into jquery Click delegates event here, but into delegating a function call like how it works in c#

Let me know

like image 703
Stacknerd Avatar asked Apr 12 '15 04:04

Stacknerd


People also ask

What is delegate function in JavaScript?

The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur. Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).

How do you call a function using delegates?

A delegate can be declared using the delegate keyword followed by a function signature, as shown below. The following declares a delegate named MyDelegate . public delegate void MyDelegate(string msg); Above, we have declared a delegate MyDelegate with a void return type and a string parameter.

Are there delegates in JavaScript?

Event Delegation is basically a pattern to handle events efficiently. Instead of adding an event listener to each and every similar element, we can add an event listener to a parent element and call an event on a particular target using the . target property of the event object.

What is the difference between delegate and callback?

Callbacks are similar in function to the delegate pattern. They do the same thing: letting other objects know when something happened, and passing data around. What differentiates them from the delegate pattern, is that instead of passing a reference to yourself, you are passing a function.


2 Answers

What you are looking for is an "Observer Pattern", as described eg. here.

But as you are interested in jQuery, you don't need to go the trouble of writing an observer pattern for yourself. jQuery already implements an observer in the guise of its .on() method, which can be invoked on a jQuery collection to cause callback function(s) to fire every time a native or custom event is dispatched.

Here's an example :

$(function() {
    //attach a custom event handler to the document
    $(document).on('valueChange', function (evt) {
        $(this).find("#s0").text(evt.type);
        $(this).find("#s1").text(evt.value);
        $(this).find("#s2").text(evt.change);
        $(this).find("#s3").text(evt.timestamp).toLocaleString();
    });

    //customEvent(): a utility function that returns a jQuery Event, with custom type and data properties
    //This is necessary for the dispatch an event with data
    function customEvent(type, data) {
        return $.extend($.Event(type||''), data||{});
    };

    //randomUpdate(): fetches data and broadcasts it in the form of a 'changeValue' custom event
    //(for demo purposes, the data is randomly generated)
    function randomUpdate() {
        var event = customEvent('valueChange', {
            value: (10 + Math.random() * 20).toFixed(2),
            change: (-3 + Math.random() * 6).toFixed(2),
            timestamp: new Date()
        });
        $(document).trigger(event);//broadcast the event to the document
    }
});

Here's a demo, complete with "start" and "stop" buttons for a regular "interval" dispatch of the custom event.

Notes

  • Under some circumstances, it might be more appropriate to broadcast the event to the four data spans individually.
  • On the web, you will find mention of a more convenient jQuery.event.trigger({...}) syntax. Unfortunately this was an undocumented feature of jQuery, which disappeared at v1.9 or thereabouts.
like image 79
Roamer-1888 Avatar answered Sep 20 '22 22:09

Roamer-1888


Although the original question was ansered by solving the root problem (observer - pattern) there is a way to implement delegates in JavaScript.

The C# delegate pattern is available in native JavaScript using context binding. Context binding in JavaScript is done with the .call method. The function will be called in the context given by the first argument. Example:

function calledFunc() {
  console.log(this.someProp);
}

var myObject = {
  someProp : 42,
  doSomething : function() {
    calledFunc.call(this);
  }
}

myObject.doSomething();
// will write 42 to console;
like image 41
theking2 Avatar answered Sep 23 '22 22:09

theking2