Event.observe

Event.observe

View source on GitHub →

Event.observe(element, eventName, handler) → Element
  • element (Element | String) – The DOM element to observe, or its ID.
  • eventName (String) – The name of the event, in all lower case, without the "on" prefix — e.g., "click" (not "onclick").
  • handler (Function) – The function to call when the event occurs.

Registers an event handler on a DOM element. Aliased as Element#observe.

Event.observe smooths out a variety of differences between browsers and provides some handy additional features as well. Key features in brief: * Several handlers can be registered for the same event on the same element. * Prototype figures out whether to use addEventListener (W3C standard) or attachEvent (MSIE); you don't have to worry about it. * The handler is passed an extended Event object (even on MSIE). * The handler's context (this value) is set to the extended element being observed (even if the event actually occurred on a descendent element and bubbled up). * Prototype handles cleaning up the handler when leaving the page (important for MSIE memory leak prevention). * Event.observe makes it possible to stop observing the event easily viaEvent.stopObserving. * Adds support for mouseenter / mouseleave events in all browsers.

Although you can use Event.observe directly and there are times when that's the most convenient or direct way, it's more common to use its alias Element#observe. These two statements have the same effect:

Event.observe('foo', 'click', myHandler);
$('foo').observe('click', myHandler);

The examples in this documentation use the Element#observe form.

The Handler

Signature:

function handler(event) {
  // `this` = the element being observed
}

So for example, this will turn the background of the element 'foo' blue when it's clicked:

$('foo').observe('click', function(event) {
  this.setStyle({backgroundColor: 'blue'});
});

Note that we used this to refer to the element, and that we received the eventobject as a parameter (even on MSIE).

It's All About Timing

One of the most common errors trying to observe events is trying to do it before the element exists in the DOM. Don't try to observe elements until after the dom:loadedevent or window load event has been fired.

Preventing the Default Event Action and Bubbling

If we want to stop the event (e.g., prevent its default action and stop it bubbling), we can do so with the extended event object's Event#stop method:

$('foo').observe('click', function(event) {
  event.stop();
});
Finding the Element Where the Event Occurred

Since most events bubble from descendant elements up through the hierarchy until they're handled, we can observe an event on a container rather than individual elements within the container. This is sometimes called "event delegation". It's particularly handy for tables:

<table id='records'>
  <thead>
    <tr><th colspan='2'>No record clicked</th></tr>
  </thead>
  <tbody>
    <tr data-recnum='1'><td>1</td><td>First record</td></tr>
    <tr data-recnum='2'><td>2</td><td>Second record</td></tr>
    <tr data-recnum='3'><td>3</td><td>Third record</td></tr>
  </tbody>
</table>

Instead of observing each cell or row, we can simply observe the table:

$('records').observe('click', function(event) {
  var clickedRow = event.findElement('tr');
  if (clickedRow) {
    this.down('th').update("You clicked record #" + clickedRow.readAttribute("data-recnum"));
  }
});

When any row in the table is clicked, we update the table's first header cell saying which record was clicked. Event#findElement finds the row that was clicked, and this refers to the table we were observing.

Stopping Observing the Event

If we don't need to observe the event anymore, we can stop observing it withEvent.stopObserving or its Element#stopObserving alias.

Using an Instance Method as a Handler

If we want to use an instance method as a handler, we will probably want to useFunction#bind to set the handler's context; otherwise, the context will be lost andthis won't mean what we expect it to mean within the handler function. E.g.:

var MyClass = Class.create({
  initialize: function(name, element) {
    this.name = name;
    element = $(element);
    if (element) {
      element.observe(this.handleClick.bind(this));
    }
  },
  handleClick: function(event) {
    alert("My name is " + this.name);
  },
});

Without the Function#bind, when handleClick was triggered by the event, thiswouldn't refer to the instance and so the alert wouldn't show the name. Because we used Function#bind, it works correctly. See Function#bind for details. There's alsoFunction#bindAsEventListener, which is handy for certain very specific situations. (Normally, Function#bind is all you need.)

Side Notes

Although Prototype smooths out most of the differences between browsers, the fundamental behavior of a browser implementation isn't changed. For example, the timing of the change or blur events varies a bit from browser to browser.

Changes in 1.6.x

Prior to Prototype 1.6, Event.observe supported a fourth argument (useCapture), a boolean that indicated whether to use the browser's capturing phase or its bubbling phase. Since MSIE does not support the capturing phase, we removed this argument from 1.6, lest it give users the false impression that they can use the capturing phase in all browsers.

1.6 also introduced setting the this context to the element being observed, automatically extending the Event object, and the Event#findElement method.

原文:http://prototypejs.org/doc/latest/dom/Event/observe/index.html

转载于:https://www.cnblogs.com/saysmy/archive/2012/12/26/5594894.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以在后端代码中使用分页查询,如下所示: ```java @Query("select approvalRecord from ApprovalRecord approvalRecord inner join ApprovalRecordItem approvalRecordItem on approvalRecord = approvalRecordItem.approvalRecord where approvalRecordItem.status <> 'AUDITING' and approvalRecordItem.createdBy.login = ?#{principal.username} order by approvalRecordItem.id desc") Page<ApprovalRecord> findAuditedByCurrentUser(Pageable pageable); ``` 然后在前端代码中调用分页查询接口,并在请求参数中传递分页参数,如下所示: ```typescript queryAuditing(req?: any): Observable<HttpResponse<IApprovalRecord[]>> { const options = createRequestOption(req); return this.http.get<IApprovalRecord[]>(`${this.resourceUrl}/my-auditing`, { params: options, observe: 'response' }); } loadAll(page: number): void { const pageSize = 10; // 每页显示的数据数量 this.approvalRecordService.queryAuditing({ page: page.toString(), size: pageSize.toString() }).subscribe((res: HttpResponse<IApprovalRecord[]>) => { this.auditingApprovalRecords = res.body ?? []; }); } ``` 注意,在调用分页查询接口时,需要传递 `page` 和 `size` 参数,分别表示当前页数和每页显示的数据数量。在前端代码中,可以使用一个函数来处理分页按钮的点击事件,如下所示: ```typescript loadPage(page: number): void { this.page = page; this.loadAll(this.page - 1); // 注意:后端接口的页数是从 0 开始计算的,所以这里需要减去 1 } ``` 然后在模板中使用 `ngx-pagination` 组件来显示分页按钮,如下所示: ```html <div class="row justify-content-center"> <jhi-item-count [page]="page" [itemsPerPage]="itemsPerPage" [totalItems]="totalItems" [queryCount]="true"></jhi-item-count> </div> <div class="row justify-content-center"> <jhi-pagination [page]="page" [pageCount]="pageCount" [maxSize]="5" (pageChange)="loadPage($event)"></jhi-pagination> </div> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值