如何将javascript函数附加到另一个javascript函数?

时间:2014-02-07 14:14:27

标签: javascript function events listener

如果要调用并执行另一个特定的javascript函数,我怎么定义调用javascript函数?

var UploadStatusController= {
var uploadedcount,

    UpdateStatus: function (numberOfUploadedFiles) {
     UploadStatusController.uploadedcount += numberOfUploadedFiles;
    });
},


var DisplayController{
UpdateInfoBox: function () {
      $('#Infobox').InnerHtml = UploadStatusController.uploadedcount;

    });
}

我不想从UploadStatusController调用我的DisplayController, 而且我也不想将DisplayController作为变量传递给UploadStatusController。 相反,我正在寻找一种方法将我的函数绑定到另一个函数上的调用,其方式类似于将其绑定到文档事件。

1 个答案:

答案 0 :(得分:0)

var uploadStatusController = {};
(function () {
    var subscribers = [];

    var uploadedCount = 0;

    uploadStatusController.updateStatus = function (numberOfUploadedFiles) {
        uploadedCount += numberOfUploadedFiles;

        // call subscribers
        callSubscribers();
    };

    uploadStatusController.subscribe = function (fn) {
        subscribers.push(fn);
    };
    function callSubscribers() {
        for (var i = 0, len = subscribers.length; i < len; i++) {
            subscribers[i].apply(this, [uploadedCount]);
        }
    };
}());

// subscribe to event from anywhere you need
uploadStatusController.subscribe(function (uploadedCount) {
    console.log(uploadedCount);
});