你能用 jquery 触发器设置 event.data

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9584892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:00:43  来源:igfitidea点击:

Can you set event.data with jquery trigger

jquery

提问by 9-bits

With jQuery .on()you can pass an optional parameter to set the event data. Can you do this with trigger as well?

使用 jQuery,.on()您可以传递一个可选参数来设置事件数据。你也可以用触发器来做到这一点吗?

回答by TxRegex

Short Answer:

简答:

Can trigger()pass data to your event handlers? Yes(as additional parameters)

可以触发()将数据传递到您的事件处理程序?(作为附加参数)

Can trigger()pass data into the event.data object directly? No(only on()does this)

trigger()可以直接将数据传入 event.data 对象吗?(仅on()执行此操作)

// Using this will pass myData to every event handler as the second parameter. 
trigger('myEvent', [myData]) 
// Instead of this
on('myEvent', function(evt) {...});
// You would do this
on('myEvent', function(evt, myData) {...});

Long Answer

长答案

The trigger() methoddoes 5 main things.

trigger() 方法主要做了 5 件事。

  1. It creates a JQueryEventObject with the type and optional namespace you give it
  2. It sends or emits an event of a specific type that travels up the DOM until it reaches the top or its propagation is stopped.
  3. It defines the signature of event handlers for that type of event.
    • function(event) {...} is the default
  4. It passes the event as the first parameter to those handlers
  5. It (optionally) passes additional parameters to any handlers of the event
    • function(event, additionalParams) {}
  1. 它使用您提供的类型和可选命名空间创建一个 JQueryEventObject
  2. 它发送或发出特定类型的事件,该事件沿 DOM 向上传播,直到到达顶部或传播停止。
  3. 它定义了该类型事件的事件处理程序的签名。
    • function(event) {...} 是默认值
  4. 它将事件作为第一个参数传递给这些处理程序
  5. 它(可选)将附加参数传递给事件的任何处理程序
    • 功能(事件,附加参数){}

Numbers 3 and 5 are most important and relevant to you. Since you implicitly define the api for handling this event, you want to be consistent with how you trigger events so that people who use your code can be consistent with how they use it.

数字 3 和 5 对您来说是最重要和最相关的。由于您隐式定义了用于处理此事件的 api,因此您希望与触发事件的方式保持一致,以便使用您代码的人可以与他们使用它的方式保持一致。

Example 1Consistency

示例 1一致性

function Car(speed, tires, brakes) {
    this.speed = speed;
    this.tires = tires;
    this.brakes = brakes;
}

Car.prototype.brake = function(amount) {
    // You can do this (Event handler will have access to these parameters)
    car.trigger('brake.car', [this.speed, this.brakes, this.tires, amount])
    // Or this (Event handler will have access to these parameters)
    car.trigger('brake.car', [this, amount])
    // but try not to mix and match with the same event type
}
...
//This is the first way from above (choose one or the other, but don't mix and match).
passenger.on('brake.car', {person: passenger}, function(evt, carSpeed, carBrakes, carTires, brakeAmount){
    if(brakeAmount > 50)
        passenger.hangOnTight();
    }
})

...
// This is the second way from above (choose one or the other, but don't mix and match).
passenger.on('brake.car', function(evt, car, brakeAmount){
    if(brakeAmount > 50)
        passenger.hangOnTight();
    }
})

Example 2Here is the typical example showing both trigger() and on():

示例 2以下是显示 trigger() 和 on() 的典型示例:

jQuery(document).on('eventName' {eventData1: 'foo', eventData2: 'bar'}, function (evt, extraParam1, extraParam2) {
    //This code runs when the event is triggered
    console.log(evt.data.eventData1) // foo
    console.log(evt.data.eventData2) // bar
    console.log(extraParam1) // 'extra param 1'
    console.log(extraParam2) // 'extra param 2'
});

jQuery(document).trigger('eventName', ['extra param 1', 'extra param 2']);

So just remember.

所以只要记住。

  • .trigger(): emit the event and define parameter 2, 3, etc consistently if needed
  • .on(): event is bubbling up the dom. do some stuff, add to or use event data and use the extra params that trigger added or not.

  • Tangent: If you want to define event handlers for dynamic elements that can be added or removed arbitrarily, this is very easy with jQuery. See this answer: In jQuery, how to attach events to dynamic html elements?

  • .trigger():发出事件并在需要时一致地定义参数 2、3 等
  • .on(): 事件正在冒泡 dom。做一些事情,添加或使用事件数据并使用触发添加或不添加的额外参数。

  • Tangent:如果要为可以任意添加或删除的动态元素定义事件处理程序,使用 jQuery 非常容易。请参阅此答案:在 jQuery 中,如何将事件附加到动态 html 元素?

回答by Harti

I hope I didn't get you wrong but do you mean passing additional data with the triggermethod?

我希望我没有误会你的意思,但你的意思是用这个trigger方法传递额外的数据吗?

$(app.Model).trigger("foo", additionalData);

And somewhere else...

还有别的地方...

$(app.Model).on("foo", callback);

var callback = function(event, additionalData) {
   console.log(additionalData);
}

Note that if you pass additional data with trigger, your first parameter in the callback function always is the actual event you are triggering.

请注意,如果您使用 传递附加数据trigger,则回调函数中的第一个参数始终是您触发的实际事件。

The app.ModelI used in the parenthesis is the object that should trigger an event and that also listens on that event. Think of it as kind of a namespace. You can always use document, any DOM selector or even object you like, just make sure that both the triggerand the onmust use the sameobject (that is, DOM elements that are removed from the DOM temporarily are error-prone).

app.Model括号中的I 是应该触发事件并侦听该事件的对象。将其视为一种命名空间。您始终可以使用document、任何 DOM 选择器甚至您喜欢的对象,只需确保 thetrigger和 theon必须使用相同的对象(即,临时从 DOM 中删除的 DOM 元素容易出错)。

回答by Siva Charan

You can do this way:-

你可以这样做:-

Example

例子

  //Create a new jQuery.Event object without the "new" operator.
  var e = jQuery.Event("click");

  // trigger an artificial click event
  jQuery("body").trigger( e );

You can pass event.data too with the same approach. Refer this Event Object

您也可以使用相同的方法传递 event.data。参考这个事件对象

回答by Dave

This was the approach I took.

这是我采取的方法。

$('#foo').on('click', { init: false }, function(e, data) {
        data = data || e.data;
        console.log(data.init); // will be true in the trigger, and false in the click.
    })
    .trigger('click', { init: true });

回答by Starx

I know an workaround we can use for this

我知道我们可以使用的解决方法

$("button").on("click", function(event) {
   event.data = $(this).data('events'); // get the data value 
   alert(event.data); //use your data as you want
});


//Now set the data value and trigger
$("button").data('events','youreventsvalue').trigger("click");

Here is a demo

这是一个演示

回答by Rafael Verger

In jQuery site you can see the declaration for the triggerfunction: .trigger( eventType [, extraParameters] )

在 jQuery 站点中,您可以看到该trigger函数的声明:.trigger( eventType [, extraParameters] )

The extraParametersmust be an array or a single object and you will be allowed to get these objects with arguments[1+] (arguments[0] is equal to event object).

extraParameters必须是一个数组或一个单一的对象,你将被允许获得与参数这些对象[1+(参数[0]等于事件对象)。

So, here's an example:

所以,这是一个例子:

$('#foo').bind('custom', function(event) {
  if ( arguments.length > 1 ) {
    $.each(arguments, function(i,arg){
      alert("element " + i + " is " + arg);
    })
  }
});

$('#foo').trigger('custom', ['Custom', 'Event', { 'test' : 'attr from object' }, 123]);

回答by yoav barnea

As far as I know, the same dataObjectthat you defined with the original :

据我所知,与dataObject您使用原始定义的相同:

$('selector').on('eventName', dataObject , functionName)

will be also sent when you use `$('selector').trigger('eventName').

当你使用 `$('selector').trigger('eventName') 时也会被发送。

you can also pass parameters (like other mentions in their answers) but those parameters will be additional arguments (you will still have the dataObjectyou set in the .on()function).

您还可以传递参数(就像他们答案中的其他提及一样),但这些参数将是附加参数(您仍然可以dataObject.on()函数中设置您的参数)。

回答by bububaba

Yes. The documentation says:

是的。文档说:

.trigger( eventType [, extraParameters] )

Note the difference between the extra parameters we're passing here and the eventDataparameter to the .bind()method. Both are mechanisms for passing information to an event handler, but the extraParametersargument to .trigger()allows information to be determined at the time the event is triggered, while the eventDataargument to .bind()requires the information to be already computed at the time the handler is bound.

.trigger( eventType [, extraParameters] )

请注意我们在此处传递的额外参数与传递eventData.bind()方法的参数之间的区别。两者都是将信息传递给事件处理程序的机制,但extraParameters参数 to.trigger()允许在触发事件时确定信息,而eventData参数 to.bind()要求在绑定处理程序时已经计算信息。

回答by Hai Phan

It took me a while to understand the philosophy behind this. An event involves two entities: listener and dispatcher. The event.datafield was intended to be used by the listener only. It's sort of like assigning a name to a phone number:

我花了一段时间才理解这背后的哲学。一个事件涉及两个实体:侦听器和调度器。该event.data字段仅供侦听器使用。这有点像为电话号码分配一个名字:

$("(818)548-2733").on("incomingcall", null, "Mom", pickup);

You could pick up the phone and wait for the other side to tell you that she is your Mom. Or you can use event.datato attach the extra information relevant to this event.

你可以拿起电话,等对方告诉你她是你妈妈。或者您可以使用event.data附加与此事件相关的额外信息。

The $.triggerand $.triggerHandlermethods are called by the dispatcher side of an event. That's why they don't let you specify the event.data. Instead, you can use their extraParametersargument.

$.trigger$.triggerHandler方法由一个事件的调度员一边叫。这就是为什么他们不允许您指定event.data. 相反,您可以使用他们的extraParameters论点。

回答by Lord Nighton

$("pressedButton").on("click", function(event) {
   var buttonID = $(this).data('buttonID');
   alert(buttonID); // alerts 'save' string passed as an argument
});

$("pressedButton").data('buttonID','save').trigger("click");