【问题标题】:overriding fullcalendar javascript functions which is in another script覆盖另一个脚本中的fullcalendar javascript函数
【发布时间】:2016-05-07 20:09:34
【问题描述】:

我是 js 的新手,我想覆盖/覆盖另一个脚本 (my-fullcalendar.js) 中的一些 fullcalendar 函数,以便为自己做一些更改。例如函数名称是:

formatRange 和 oldMomentFormat。

formatRange 可以通过 this.$.fullCalendar.formatRange 访问,但 oldMomentFormat 不能通过这种链访问。但即使我在 my-fullcalendar.js 中做这样的事情:

;(function () {
      function MyformatRange(date1, date2, formatStr, separator, isRTL) {
          console.log( "MyformatRange");
          //other parts is exactly the same
          // ...
      }
      this.$.fullCalendar.formatRange=MyformatRange;
      console.log(this);
})();

什么都没有发生,因为没有生成日志,甚至逐行跟踪也没有从这里通过。但是当在控制台日志中观察“this”时,MyformatRange 被原始 formatRange 替换。 另一个问题是如何覆盖/覆盖不在窗口层次结构中访问的 oldMomentFormat 函数(或者我找不到它)??

【问题讨论】:

  • 该代码应该可以工作。确保以正确的顺序加载所有内容。
  • 我如何确定所有内容都以正确的顺序加载?我的 js 脚本按以下顺序排列: 。那么oldMomentFormat呢??

标签: javascript fullcalendar overriding overwrite


【解决方案1】:

好的,让我们简化问题。本质上,你有这种情况:

var makeFunObject = function () {
  var doSomething = function (msg) {
    console.log(msg);
  };

  var haveFun = function () {
    doSomething( "fun!");
  };

  return {
    doSomething : doSomething,
    haveFun : haveFun
  };
};

换句话说,您有一个正在创建闭包的函数。在该闭包内有两个“私有”函数,其中一个调用另一个。但是这两个函数似乎都在返回的对象中“暴露”了。

你写了一些代码:

var myFunObject = makeFunObject();
myFunObject.haveFun(); // fun!

是的,似乎工作得很好。现在让我们替换返回的对象中的doSomething 函数并再次调用haveFun

myFunObject.doSomething = function (msg) {
  console.log("My new function: " + msg);
};
myFunObject.haveFun(); // fun! <== wait what?

但是等等!新的替换函数没有被调用!没错:haveFun 函数是专门为调用内部函数而编写的。它实际上对对象中暴露的函数一无所知。

那是因为您无法以这种方式替换内部的私有函数(实际上,您根本无法替换它,除非更改原始代码)。

现在回到 FullCalendar 代码:您正在替换对象中的外部函数,但内部函数是由 FullCalendar 内的所有其他函数调用的

【讨论】:

  • 所以你的意思是没有办法覆盖 formatRange 和 oldMomentFormat 并为 fullCalendar 编写插件??我的目的是将我的更改作为 fullCalendar 的插件,而不是更改原始代码。
  • 这里有两个问题。 1. 无法从外部覆盖这些功能。 2. 当然,您可以为 FullCalendar 编写插件,就像为 jQuery 本身编写插件一样。但是在这样做时,您必须接受它在内部所做的事情;实际上,您提供的功能超出了它已经提供的功能,并且已经存在的功能不会“知道”该插件..
【解决方案2】:

我意识到这是一个老问题,但是当我想覆盖 getEventTimeText 函数时,我正试图解决同样的问题。

我能够从我自己的 JS 文件中完成此操作,如下所示:

$.fullCalendar.Grid.mixin({
    getEventTimeText: function (range, formatStr, displayEnd) {
        //custom version of this function
    }
});

因此,就您尝试覆盖的功能而言,您应该能够做到:

$.fullCalendar.View.mixin({
    formatRange: function (range, formatStr, separator) {
        //custom formatRange function
    }
});

注意:确保它在您实际创建日历之前运行。另请注意,您需要确保在正确的位置覆盖该函数。例如,getEventTimeText$.fullCalendar.Grid 中,而formatRange$.fullCalendar.View 中。

希望这对最终解决这个问题的其他人有所帮助。

【讨论】:

    猜你喜欢
    • 2011-05-02
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2013-10-31
    • 2012-11-15
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多