微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

可以使用jquery触发器设置event.data

使用jquery .on()可以传递一个可选参数来设置事件数据。你能用扳机做到这一点吗?

解决方法

简答:

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

可以直接将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) {...});

长答案

trigger()方法有5个主要的东西。

>它创建一个JQueryEventObject类型和可选的命名空间
>它发送或发出一个特定类型的事件,它沿着DOM向上移动,直到它到达顶部或者它的传播被停止。
>它定义了该类事件的事件处理程序的签名。

> function(event){…}是认值

>它将事件作为第一个参数传递给这些处理程序
>它(可选)将附加参数传递给事件的任何处理程序

> function(event,additionalParams){}

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

实施例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},carSpeed,carBrakes,carTires,brakeAmount){
    if(brakeAmount > 50)
        passenger.hangOnTight();
    }
})

...
// This is the second way from above (choose one or the other,car,brakeAmount){
    if(brakeAmount > 50)
        passenger.hangOnTight();
    }
})

示例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']);

所以只要记住。

> .trigger():如果需要,发出事件并定义参数2,3等> .on():event是冒泡的dom。做一些东西,添加或使用事件数据,并使用触发添加或不添加的额外的参数。

原文地址:https://www.jb51.cc/jquery/185100.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐