2

If I have a list of functions that are serving as event subscriptions, is there an advantage to running through them and calling them with .call() (B below), or more directly (A)? The code is below. The only difference I can see is that with .call you can control what this is set to. Is there any other difference besides that?

    $(function() {
        eventRaiser.subscribe(function() { alert("Hello"); });
        eventRaiser.subscribe(function(dt) { alert(dt.toString()); });

        eventRaiser.DoIt();
    });

    var eventRaiser = new (function() {
        var events = [];
        this.subscribe = function(func) {
            events.push(func);
        };

        this.DoIt = function() {
            var now = new Date();
            alert("Doing Something Useful");
            for (var i = 0; i < events.length; i++) {
                events[i](now);  //A
                events[i].call(this, now);  //B
            }
        };
    })();
0

2 Answers 2

3

No, there is no other difference. If you follow the second approach though, you can extend subscribe so that the "clients" can specify the context to be used:

this.subscribe = function(func, context) {
     events.push({func: func, context: context || this});
};

this.DoIt = function() {
    var now = new Date();
    alert("Doing Something Useful");
    for (var i = 0; i < events.length; i++) {
        events[i].func.call(events[i].context, now);
    }
 };
Sign up to request clarification or add additional context in comments.

Comments

1

If you decide to go with method B, you can allow the function that subscribes to the event, to perform event specific functions.

For instance, you could use this.getDate() inside your function (you would have to create the method) instead of passing the date as a parameter. Another helpful method inside an Event class would be this.getTarget().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.