jQuery의 맞춤 이벤트?
jquery에서 사용자 정의 이벤트 처리를 가장 잘 구현하는 방법에 대한 정보를 찾고 있습니다. 'click'등과 같은 dom 요소에서 이벤트를 연결하는 방법을 알고 있지만 미리보기 기능을 처리하기 위해 작은 자바 스크립트 라이브러리 / 플러그인을 작성하고 있습니다.
내가 가지고있는 규칙 및 데이터 / 사용자 입력 세트에서 dom 요소의 일부 텍스트를 업데이트하는 스크립트가 실행 중이지만이 스크립트가 알 수없는 다른 요소에 표시된 동일한 텍스트가 필요합니다. 내가 필요한 것은 어떻게 든 필요한 스크립트를 생성하는이 스크립트를 관찰하는 좋은 패턴입니다.
어떻게하면 되나요? 사용자 이벤트를 발생시키고 처리하기 위해 jquery의 내장 기능을 간과 했습니까? 아니면 jquery 플러그인이 필요합니까? 이것을 처리하는 가장 좋은 방법 / 플러그인은 무엇이라고 생각하십니까?
이것 좀 봐 :
( http://web.archive.org/web 의 아카이브 된 버전을 기반으로 만료 된 블로그 페이지 http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ 에서 재 인쇄 됨 /20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ )
jQuery로 게시 / 구독
2008 년 6 월 17 일
Google Gears의 오프라인 기능과 통합 된 jQuery UI를 작성하기 위해 jQuery를 사용하여 네트워크 연결 상태를 폴링하는 코드를 가지고 놀았습니다.
네트워크 감지 개체
기본 전제는 매우 간단합니다. 정기적으로 URL을 폴링 할 네트워크 감지 개체의 인스턴스를 만듭니다. 이러한 HTTP 요청이 실패하면 네트워크 연결이 끊겼거나 현재 시간에 서버에 연결할 수 없다고 가정 할 수 있습니다.
$.networkDetection = function(url,interval){
var url = url;
var interval = interval;
online = false;
this.StartPolling = function(){
this.StopPolling();
this.timer = setInterval(poll, interval);
};
this.StopPolling = function(){
clearInterval(this.timer);
};
this.setPollInterval= function(i) {
interval = i;
};
this.getOnlineStatus = function(){
return online;
};
function poll() {
$.ajax({
type: "POST",
url: url,
dataType: "text",
error: function(){
online = false;
$(document).trigger('status.networkDetection',[false]);
},
success: function(){
online = true;
$(document).trigger('status.networkDetection',[true]);
}
});
};
};
여기에서 데모를 볼 수 있습니다. 브라우저가 오프라인에서 작동하도록 설정하고 어떻게되는지 확인하십시오. 아니, 그렇게 흥미 진진하지 않습니다.
트리거 및 바인드
흥미로운 것은 (또는 적어도 흥미로운 것은) 상태가 응용 프로그램을 통해 릴레이되는 방법입니다. jQuery의 트리거 및 바인드 메소드를 사용하여 펍 / 서브 시스템을 구현하는 논의되지 않은 방법을 우연히 발견했습니다.
데모 코드는 필요한 것보다 더 모호합니다. 네트워크 감지 개체는 문서에 '상태'이벤트를 게시하여 문서를 적극적으로 수신하고 모든 가입자에게 '알림'이벤트를 게시합니다 (나중에 자세히 설명). 이 사실을 뒷받침하는 이유는 실제 응용 프로그램에서 '알림'이벤트가 게시되는시기와 방법을 제어하는 논리가 더 많을 것입니다.
$(document).bind("status.networkDetection", function(e, status){
// subscribers can be namespaced with multiple classes
subscribers = $('.subscriber.networkDetection');
// publish notify.networkDetection even to subscribers
subscribers.trigger("notify.networkDetection", [status])
/*
other logic based on network connectivity could go here
use google gears offline storage etc
maybe trigger some other events
*/
});
Because of jQuery’s DOM centric approach events are published to (triggered on) DOM elements. This can be the window or document object for general events or you can generate a jQuery object using a selector. The approach i’ve taken with the demo is to create an almost namespaced approach to defining subscribers.
DOM elements which are to be subscribers are classed simply with “subscriber” and “networkDetection”. We can then publish events only to these elements (of which there is only one in the demo) by triggering a notify event on $(“.subscriber.networkDetection”)
The #notifier
div which is part of the .subscriber.networkDetection
group of subscribers then has an anonymous function bound to it, effectively acting as a listener.
$('#notifier').bind("notify.networkDetection",function(e, online){
// the following simply demonstrates
notifier = $(this);
if(online){
if (!notifier.hasClass("online")){
$(this)
.addClass("online")
.removeClass("offline")
.text("ONLINE");
}
}else{
if (!notifier.hasClass("offline")){
$(this)
.addClass("offline")
.removeClass("online")
.text("OFFLINE");
}
};
});
So, there you go. It’s all pretty verbose and my example isn’t at all exciting. It also doesn’t showcase anything interesting you could do with these methods, but if anyone’s at all interested to dig through the source feel free. All the code is inline in the head of the demo page
The link provided in the accepted answer shows a nice way to implement the pub/sub system using jQuery, but I found the code somewhat difficult to read, so here is my simplified version of the code:
$(document).on('testEvent', function(e, eventInfo) {
subscribers = $('.subscribers-testEvent');
subscribers.trigger('testEventHandler', [eventInfo]);
});
$('#myButton').on('click', function() {
$(document).trigger('testEvent', [1011]);
});
$('#notifier1').on('testEventHandler', function(e, eventInfo) {
alert('(notifier1)The value of eventInfo is: ' + eventInfo);
});
$('#notifier2').on('testEventHandler', function(e, eventInfo) {
alert('(notifier2)The value of eventInfo is: ' + eventInfo);
});
I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):
$("p").bind("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
});
I had a similar question, but was actually looking for a different answer; I'm looking to create a custom event. For example instead of always saying this:
$('#myInput').keydown(function(ev) {
if (ev.which == 13) {
ev.preventDefault();
// Do some stuff that handles the enter key
}
});
I want to abbreviate it to this:
$('#myInput').enterKey(function() {
// Do some stuff that handles the enter key
});
trigger and bind don't tell the whole story - this is a JQuery plugin. http://docs.jquery.com/Plugins/Authoring
The "enterKey" function gets attached as a property to jQuery.fn - this is the code required:
(function($){
$('body').on('keydown', 'input', function(ev) {
if (ev.which == 13) {
var enterEv = $.extend({}, ev, { type: 'enterKey' });
return $(ev.target).trigger(enterEv);
}
});
$.fn.enterKey = function(selector, data, fn) {
return this.on('enterKey', selector, data, fn);
};
})(jQuery);
http://jsfiddle.net/b9chris/CkvuJ/4/
A nicety of the above is you can handle keyboard input gracefully on link listeners like:
$('a.button').on('click enterKey', function(ev) {
ev.preventDefault();
...
});
Edits: Updated to properly pass the right this
context to the handler, and to return any return value back from the handler to jQuery (for example in case you were looking to cancel the event and bubbling). Updated to pass a proper jQuery event object to handlers, including key code and ability to cancel event.
Old jsfiddle: http://jsfiddle.net/b9chris/VwEb9/24/
It is an old post, but I will try to update it with a new information.
To use custom events you need to bind it to some DOM element and to trigger it. So you need to use
.on() method takes an event type and an event handling function as arguments. Optionally, it can also receive event-related data as its second argument, pushing the event handling function to the third argument. Any data that is passed will be available to the event handling function in the data property of the event object. The event handling function always receives the event object as its first argument.
and
.trigger() method takes an event type as its argument. Optionally, it can also take an array of values. These values will be passed to the event handling function as arguments after the event object.
The code looks like this:
$(document).on("getMsg", {
msg: "Hello to everyone",
time: new Date()
}, function(e, param) {
console.log( e.data.msg );
console.log( e.data.time );
console.log( param );
});
$( document ).trigger("getMsg", [ "Hello guys"] );
Nice explanation can be found here and here. Why exactly this can be useful? I found how to use it in this excellent explanation from twitter engineer.
P.S. In plain javascript you can do this with new CustomEvent, but beware of IE and Safari problems.
Here is how I author custom events:
var event = jQuery.Event('customEventName);
$(element).trigger(event);
Granted, you could simply do
$(element).trigger('eventname');
But the way I wrote allows you to detect whether the user has prevented default or not by doing
var prevented = event.isDefaultPrevented();
This allows you to listen to your end-user's request to stop processing a particular event, such as if you click a button element in a form but do not want to the form to post if there is an error.
I then usually listen to events like so
$(element).off('eventname.namespace').on('eventname.namespace', function () {
...
});
Once again, you could just do
$(element).on('eventname', function () {
...
});
But I've always found this somewhat unsafe, especially if you're working in a team.
There is nothing wrong with the following:
$(element).on('eventname', function () {});
However, assume that I need to unbind this event for whatever reason (imagine a disabled button). I would then have to do
$(element).off('eventname', function () {});
This will remove all eventname
events from $(element)
. You cannot know whether someone in the future will also bind an event to that element, and you'd be inadvertently unbinding that event as well
The safe way to avoid this is to namespace your events by doing
$(element).on('eventname.namespace', function () {});
Lastly, you may have noticed that the first line was
$(element).off('eventname.namespace').on('eventname.namespace', ...)
I personally always unbind an event before binding it just to make sure that the same event handler never gets called multiple times (imagine this was the submit button on a payment form and the event had been bound 5 times)
참고URL : https://stackoverflow.com/questions/399867/custom-events-in-jquery
'IT' 카테고리의 다른 글
파이썬의 물결표 연산자 (0) | 2020.05.24 |
---|---|
의사 TTY를 할당하는 Docker -t 옵션에 대해 혼동 (0) | 2020.05.24 |
git은 특정 하위 폴더의 파일을 제외하고 특정 유형의 모든 파일을 무시합니다. (0) | 2020.05.24 |
React.js에서 컴포넌트의 소품을 업데이트 할 수 있습니까? (0) | 2020.05.24 |
개체가 특정 유형이라고 가정 (0) | 2020.05.24 |