在 Javascript 中委托函数调用

Sta*_*erd 6 javascript delegates

在 Javascript 中有没有办法像 c# 中的那样有一个委托?

C# 中的示例

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

我想用我的 Javascript 让我的主要对象在很长一段时间内做一些事情,并偶尔拍摄一个委托以进行一些更新。所有这一切都无需更改我班级的代码本身即可针对网页进行调整。

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

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

我不知道这是否足够清楚..还没有找到这方面的资源,所以我想没有办法这样做吗?

注意:我不是在这里研究 jquery Click 委托事件,而是委托一个函数调用,就像它在 c# 中的工作方式一样

让我知道

Roa*_*888 6

您正在寻找的是“观察者模式”,如所述。在这里

但是当您对 jQuery 感兴趣时,您无需费心为自己编写观察者模式。jQuery 已经在其.on() 方法的幌子下实现了一个观察者,它可以在 jQuery 集合上调用,以在每次调度本机或自定义事件时触发回调函数。

这是一个例子:

$(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
    }
});
Run Code Online (Sandbox Code Playgroud)

这是一个演示,带有用于自定义事件的常规“间隔”调度的“开始”和“停止”按钮。

笔记

  • 在某些情况下,将事件分别广播到四个数据跨度可能更合适。
  • 在网络上,您会发现提到了更方便的jQuery.event.trigger({...})语法。不幸的是,这是 jQuery 的一个未记录的特性,它在 v1.9 或左右消失了。

  • 5年后 - 刚刚意识到 `$(this).find("#s3").text(evt.timestamp).toLocaleString();` 应该是 `$(this).find("#s3").text (evt.timestamp.toLocaleString());` (3认同)

the*_*ng2 5

虽然最初的问题是通过解决根本问题(观察者 - 模式)来回答的,但还是有一种方法可以在 JavaScript 中实现委托。

C# 委托模式在使用上下文绑定的本机 JavaScript 中可用。JavaScript 中的上下文绑定是通过 .call 方法完成的。该函数将在第一个参数给出的上下文中调用。例子:

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

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

myObject.doSomething();
// will write 42 to console;
Run Code Online (Sandbox Code Playgroud)