programing tip

ExtJS 4 이벤트 처리 설명

itbloger 2020. 7. 4. 11:08
반응형

ExtJS 4 이벤트 처리 설명


최근에 ExtJS를 배우기 시작했으며 이벤트 처리 방법을 이해하는 데 어려움이 있습니다. ExtJS의 이전 버전에 대한 경험이 없습니다.

다양한 매뉴얼, 안내서 및 설명서 페이지를 읽음으로써 사용법을 알아 냈지만 어떻게 작동하는지 잘 모르겠습니다. 이전 버전의 ExtJS에 대한 몇 가지 자습서를 찾았지만 ExtJS 4에 적용 할 수있는 방법이 확실하지 않습니다.

저는 구체적으로 다음과 같은 것들에 대한 "최종 단어"를보고 있습니다

  • 이벤트 처리 함수에는 어떤 인수가 전달됩니까? 항상 전달되는 표준 인수 세트가 있습니까?
  • 우리가 작성하는 사용자 컴포넌트에 대한 사용자 정의 이벤트를 정의하는 방법 이 맞춤 이벤트를 어떻게 시작할 수 있습니까?
  • 반환 값 (true / false)이 이벤트 버블 방식에 영향을 줍니까? 그렇지 않은 경우 이벤트 처리기 내부 또는 외부에서 이벤트 버블 링을 어떻게 제어 할 수 있습니까?
  • 이벤트 리스너를 등록하는 표준 방법이 있습니까? (지금까지 두 가지 다른 방법을 사용했으며 각 방법이 사용 된 이유를 잘 모르겠습니다).

예를 들어, 이 질문 은 이벤트 핸들러가 상당히 많은 인수를받을 수 있다고 믿게합니다. 처리기에 대한 두 가지 인수가있는 다른 자습서를 보았습니다. 어떤 변화가 있습니까?


DOM 요소의 이벤트 처리에 대해 설명하겠습니다.

DOM 노드 이벤트 처리

우선 DOM 노드로 직접 작업하고 싶지 않을 것입니다. 대신 Ext.Element인터페이스 를 사용하고 싶을 것입니다 . 할당하는 이벤트 핸들러의 목적을 위해, Element.addListener그리고 Element.on(이들은 동일)이 생성되었다. 예를 들어 html이 있다면 :

<div id="test_node"></div>

click이벤트 핸들러를 추가하고 싶습니다 .
검색하자 Element:

var el = Ext.get('test_node');

이제 click이벤트에 대한 문서를 확인하십시오 . 핸들러에는 세 가지 매개 변수가있을 수 있습니다.

click (Ext. EventObject e, HTMLElement t, Object eOpts)

이 모든 것을 알면 핸들러를 할당 할 수 있습니다.

//       event name      event handler
el.on(    'click'        , function(e, t, eOpts){
  // handling event here
});

위젯 이벤트 처리

위젯 이벤트 처리는 DOM 노드 이벤트 처리와 매우 유사합니다.

우선, 위젯 이벤트 처리는 Ext.util.Observablemixin 을 사용하여 실현됩니다 . 이벤트를 올바르게 처리하려면 위젯 Ext.util.Observable이 믹스 인으로 포함되어 있어야합니다 . 모든 내장 위젯 (예 : 패널, 양식, 트리, 격자 등)은 Ext.util.Observable기본적으로 믹스 인입니다.

위젯의 경우 핸들러를 지정하는 두 가지 방법이 있습니다. 첫 번째 방법 메소드 에서 사용 하는addListener입니다. 예를 들어 Button위젯을 생성 하고 click이벤트를 할당 해 봅시다 . 우선 핸들러의 인수에 대한 이벤트 문서를 확인해야합니다.

click (Ext.button. Button this, Event e, Object eOpts)

이제 사용하자 on:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
  // event handling here
  console.log(btn, e, eOpts);
});

두 번째 방법은 위젯의 리스너 구성 을 사용하는 것입니다 .

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  listeners : {
    click: function(btn, e, eOpts) {
      // event handling here
      console.log(btn, e, eOpts);
    }
  }
});

공지 사항이 있다는 Button위젯은 위젯의 특별한 종류이다. handlerconfig 를 사용하여 클릭 이벤트를이 위젯에 지정할 수 있습니다 .

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  handler : function(btn, e, eOpts) {
    // event handling here
    console.log(btn, e, eOpts);
  }
});

맞춤 이벤트 발생

먼저 addEvents 메소드를 사용 하여 이벤트를 등록해야합니다 .

myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);

addEvents방법을 사용하는 것은 선택 사항입니다. 이 방법에 대한 의견에서이 방법을 사용할 필요는 없지만 이벤트 문서화를위한 장소를 제공합니다.

이벤트를 발생 시키려면 fireEvent 메소드를 사용하십시오 .

myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);

arg1, arg2, arg3, /* ... */핸들러로 전달됩니다. 이제 이벤트를 처리 할 수 ​​있습니다.

myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
  // event handling here
  console.log(arg1, arg2, arg3, /* ... */);
});

addEvents 메소드 호출 을 삽입하기위한 가장 좋은 위치 initComponent는 새 위젯을 정의 할 때 위젯의 메소드 라는 것을 언급 할 가치가 있습니다.

Ext.define('MyCustomButton', {
  extend: 'Ext.button.Button',
  // ... other configs,
  initComponent: function(){
    this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
    // ...
    this.callParent(arguments);
  }
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });

이벤트 버블 링 방지

To prevent bubbling you can return false or use Ext.EventObject.preventDefault(). In order to prevent browser's default action use Ext.EventObject.stopPropagation().

For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:

myButton.on('click', function(btn, e){
  if (e.button !== 0)
    e.preventDefault();
});

Firing application wide events

How to make controllers talk to each other ...

In addition to the very great answer above I want to mention application wide events which can be very useful in an MVC setup to enable communication between controllers. (extjs4.1)

Lets say we have a controller Station (Sencha MVC examples) with a select box:

Ext.define('Pandora.controller.Station', {
    extend: 'Ext.app.Controller',
    ...

    init: function() {
        this.control({
            'stationslist': {
                selectionchange: this.onStationSelect
            },
            ...
        });
    },

    ...

    onStationSelect: function(selModel, selection) {
        this.application.fireEvent('stationstart', selection[0]);
    },    
   ...
});

When the select box triggers a change event, the function onStationSelect is fired.

Within that function we see:

this.application.fireEvent('stationstart', selection[0]);

This creates and fires an application wide event that we can listen to from any other controller.

Thus in another controller we can now know when the station select box has been changed. This is done through listening to this.application.on as follows:

Ext.define('Pandora.controller.Song', {
    extend: 'Ext.app.Controller', 
    ...
    init: function() {
        this.control({
            'recentlyplayedscroller': {
                selectionchange: this.onSongSelect
            }
        });

        // Listen for an application wide event
        this.application.on({
            stationstart: this.onStationStart, 
                scope: this
        });
    },
    ....
    onStationStart: function(station) {
        console.info('I called to inform you that the Station controller select box just has been changed');
        console.info('Now what do you want to do next?');
    },
}

If the selectbox has been changed we now fire the function onStationStart in the controller Song also ...

From the Sencha docs:

Application events are extremely useful for events that have many controllers. Instead of listening for the same view event in each of these controllers, only one controller listens for the view event and fires an application-wide event that the others can listen for. This also allows controllers to communicate with one another without knowing about or depending on each other’s existence.

In my case: Clicking on a tree node to update data in a grid panel.

Update 2016 thanks to @gm2008 from the comments below:

In terms of firing application-wide custom events, there is a new method now after ExtJS V5.1 is published, which is using Ext.GlobalEvents.

When you fire events, you can call: Ext.GlobalEvents.fireEvent('custom_event');

When you register a handler of the event, you call: Ext.GlobalEvents.on('custom_event', function(arguments){/* handler codes*/}, scope);

This method is not limited to controllers. Any component can handle a custom event through putting the component object as the input parameter scope.

Found in Sencha Docs: MVC Part 2


One more trick for controller event listeners.

You can use wildcards to watch for an event from any component:

this.control({
   '*':{ 
       myCustomEvent: this.doSomething
   }
});

Just wanted to add a couple of pence to the excellent answers above: If you are working on pre Extjs 4.1, and don't have application wide events but need them, I've been using a very simple technique that might help: Create a simple object extending Observable, and define any app wide events you might need in it. You can then fire those events from anywhere in your app, including actual html dom element and listen to them from any component by relaying the required elements from that component.

Ext.define('Lib.MessageBus', {
    extend: 'Ext.util.Observable',

    constructor: function() {
        this.addEvents(
            /*
             * describe the event
             */
                  "eventname"

            );
        this.callParent(arguments);
    }
});

Then you can, from any other component:

 this.relayEvents(MesageBus, ['event1', 'event2'])

And fire them from any component or dom element:

 MessageBus.fireEvent('event1', somearg);

 <input type="button onclick="MessageBus.fireEvent('event2', 'somearg')">

Just two more things I found helpful to know, even if they are not part of the question, really.

You can use the relayEvents method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load event. It is quite handy when writing custom components that encapsulate several sub-components.

The other way around, i.e. passing on events received by an encapsulating component mycmp to one of its sub-components subcmp, can be done like this

mycmp.on('show' function (mycmp, eOpts)
{
   mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});

참고URL : https://stackoverflow.com/questions/7260134/explain-extjs-4-event-handling

반응형