简体   繁体   English

在 Javascript 中调用另一个函数

[英]Call function within another in Javascript

I've the following script:我有以下脚本:

gapi.analytics.ready(function() {
  viewSelector.on('viewChange', function update (data) {
  var title = document.getElementById('view-name');
  title.innerHTML = data.property.name + ' (' + data.view.name + ')';

  activeUsers.set(data).execute();
  renderWeekOverWeekChart(data.ids);
  renderTopBrowsersChart(data.ids);
  renderTopCountriesChart(data.ids);

  setTimeout(function() {
    var list = document.getElementsByTagName("tr")[0];
    list.getElementsByTagName("th")[0].innerHTML = "Pagina's";
    list.getElementsByTagName("th")[1].innerHTML = "Paginaweergaven";
  }, 500); 
 });
});

And within the following code I would like to re-run the update();在下面的代码中,我想重新运行 update(); function.功能。

function datumwissel( datumbtn ) {
 if ( datumbtn.className == 'maand' ) {
    datumbtn.className = 'jaar';
    dimensions1 =  'ga:month,ga:nthMonth';
    start1 = moment(now).date(1).month(0).format('YYYY-MM-DD');
    end1 = moment(now).format('YYYY-MM-DD');
    start2 = moment(now).subtract(1, 'year').date(1).month(0).format('YYYY-MM-DD');
    end2 = moment(now).date(1).month(0).subtract(1, 'day').format('YYYY-MM-DD');
    format1 = 'M';
    format2 = 'MMM';
    update();
 } 
 else {
    datumbtn.className = 'maand';
    dimensions1 =  'ga:date,ga:nthWeek';
    start1 = moment(now).subtract(2, 'day').date(1).format('YYYY-MM-DD');
    end1 = moment(now).format('YYYY-MM-DD');
    start2 = moment(now).subtract(2, 'day').date(1).subtract(1, 'month').format('YYYY-MM-DD');
    end2 = moment(now).subtract(2, 'day').date(1).subtract(1, 'day').format('YYYY-MM-DD');
    format1 = 'YYYYMMDD';
    format2 = 'Do';
    update();
  }
 }  

But somehow this doesn't work.但不知何故,这不起作用。 I also tried in the above script: window.update = function (data) {} .我也在上面的脚本中尝试过: window.update = function (data) {} But that also doesn't work.但这也行不通。

How can I call the update();我如何调用update(); function that is situated inside the gapi.analytics.ready(function() {} ?位于gapi.analytics.ready(function() {}内的gapi.analytics.ready(function() {}

Important is that I cannot make it globally as it has to be situated inside the gapi.analytics.ready().重要的是我不能在全球范围内制作它,因为它必须位于 gapi.analytics.ready() 内。

It's really a simple matter of moving the function declaration移动函数声明真的很简单

function update (data) {
  // same as existing code
}

gapi.analytics.ready(function() {
  viewSelector.on('viewChange', update );
});

And passing in data needed when you call it in your other function并在您在其他函数中调用它时传递所需的数据

function datumwissel( datumbtn ) {
 if ( datumbtn.className == 'maand' ) {
    ..........

    update(datumbtn);
 }....... 

Important is that I cannot make it globally as it has to be situated inside the gapi.analytics.ready()重要的是我不能在全球范围内制作它,因为它必须位于 gapi.analytics.ready() 内

That's not actually true - you can have it global and there at the same time.这实际上不是真的 - 你可以同时在全球范围内使用它。 Whether you want to, is a different manner, as that would pollute the global namespace and so on.是否愿意,是一种不同的方式,因为这会污染全局命名空间等等。 However, here is how that can be achieved:但是,这是如何实现的:

First, extract the update function outside of the ready handler like so首先,像这样在ready处理程序之外提取更新函数

function update (data) {
  var title = document.getElementById('view-name');
  title.innerHTML = data.property.name + ' (' + data.view.name + ')';

  activeUsers.set(data).execute();
  renderWeekOverWeekChart(data.ids);
  renderTopBrowsersChart(data.ids);
  renderTopCountriesChart(data.ids);

  setTimeout(function() {
    var list = document.getElementsByTagName("tr")[0];
    list.getElementsByTagName("th")[0].innerHTML = "Pagina's";
    list.getElementsByTagName("th")[1].innerHTML = "Paginaweergaven";
  }, 500); 
 }

This will create a new function with the name update which accepts one parameter called data .这将创建一个名为update的新函数,它接受一个名为data参数。 Thanks to hoisting it would not matter if it's before or after anywhere you want to use it, as it would be effectively "pulled" to the top.多亏了提升,它在您想要使用它的任何地方之前或之后都无关紧要,因为它会被有效地“拉”到顶部。

Next, you can just use the function inside the ready handler like so:接下来,您可以像这样在ready处理程序中使用该函数:

gapi.analytics.ready(function() {
  viewSelector.on('viewChange', update);
});

Since .on(events, handler) accepts a function as the second parameter, you can just provide a function reference there.由于.on(events, handler)接受一个函数作为第二个参数,你可以在那里提供一个函数引用。 It doesn't matter that your function is technically declared elsewhere, as it is still going to be called with the same arguments.您的函数在技术上在其他地方声明并不重要,因为它仍然会使用相同的参数被调用。 Similarly, if you replace update with alert you will be giving the reference to window.alert so you will get an alert with data.同样,如果您用alert替换update ,您将提供对window.alert的引用,因此您将收到带有数据的警报。

With that, you can just call the same function in your other piece of code.这样,您就可以在另一段代码中调用相同的函数。

That is true for any place that uses callbacks, including setTimeout - you can just give a function reference and it's going to be called.对于任何使用回调的地方都是如此,包括setTimeout - 你可以只给出一个函数引用,它就会被调用。 Internally, those kinds of functions almost always do something like callback() or callback(someData) , occasionally callback.call(/* parameters */) where callback is the passed in argument.在内部,这些类型的函数几乎总是做类似callback()callback(someData) ,偶尔callback.call(/* parameters */)其中callback是传入的参数。 Whether you define that argument as you are calling the function, eg, selector.on("click", function() {/* code */}) or separately, eg,是在调用函数时定义该参数,例如selector.on("click", function() {/* code */})还是单独定义,例如,

function clickHandler() { /* code */ }
selector.on("click", clickHandler)

matters little.无关紧要。

With that said, whether you want the function global is a different matter.话虽如此,您是否想要全局函数是另一回事。 Unless both pieces of code are in the same place, a global function may be the easiest way.除非两段代码在同一个地方,否则全局函数可能是最简单的方法。 You could, also, namespace anything your app uses, which would partially avoid the global pollution.你也可以命名你的应用程序使用的任何东西,这将部分避免全局污染。 Not completely, but sometimes you just need to have things living under window if you have multiple files, in which case, you can define your own little corner there to play with: window.myApp = window.myApp || {}不完全,但有时如果您有多个文件,您只需要在window下放置一些东西,在这种情况下,您可以在那里定义自己的小角落: window.myApp = window.myApp || {} window.myApp = window.myApp || {} would create a new object that can serve as namespace and so you will be able to do things like myApp.update = function(data) { /* code */ } and thus share that code. window.myApp = window.myApp || {}将创建一个可用作命名空间的新对象,因此您将能够执行诸如myApp.update = function(data) { /* code */ } ,从而共享该代码。

If your two pieces of code are indeed in one file, then you merely need to create the function outside both using var update = function(data) { /* code */ } then hand it to each in the exact same way, since update is still going to be a function reference, however, if assigned to a variable, it won't be added to the global namespace (nor would the declaration be hoisted).如果您的两段代码确实在一个文件中,那么您只需要在两者之外使用var update = function(data) { /* code */ }创建函数,然后以完全相同的方式将其传递给每个文件,因为update仍然是一个函数引用,但是,如果分配给一个变量,它不会被添加到全局命名空间(也不会提升声明)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM