简体   繁体   中英

How to listen for HTTP events in backbone

A complete backbone noob question.

I was wondering, is there a way to listen to HTTP-POST events in backbone?

Lets say, when an API user does a POST request using wget from the command line I would like to update my view. I looked at the API docs and I tried the request option but had no luck. Basically in my view I am trying something like this:

this.listenTo(this.collection, 'request', this.render);

PS: I have the function definition of this.render in my code

除非服务器使用某种服务器推送技术明确通知客户端有关事件,否则一个客户端无法监听另一客户端的事件。

I'm just going to extend on @Yaroslav's answer. His answer is totally correct; you cannot explicitly do what you want. Your workflow would have to go something like this:

  1. Client does some action from outside of your webapp (such as a command line POST)
  2. Your server does whatever it was asked to do, but then notifies your client.
  3. Your Backbone view accepts the notification and re-renders (with this.render)

In terms of your server push technology, you have a few different options.

  1. Polling w/ AJAX
  2. Long-polling w/ AJAX
  3. Websockets
  4. Server-Sent Events

All of these are touched upon and explained in this blog post .

A brief summary:

Polling

Polling is when your web app asks your server for new information at a given interval. Ie, every 10 seconds your Backbone application asks if anything new has happened. This can give a max latency of your interval time, and can lead to alot of unnecessary requests

Long polling

Your client always maintains an open request to the server, which is not returned until something happens. At that time, your client can act on the new information, and then makes a new request, which again stays open until new information.

Websockets

Websockets are a bidirectional transport mechanism which enables server->client and client->server messages.

Server Sent Events

Server sent events are a uni-directional transport and part of the HTML5 spec. They allow server->client messages.

Your client should listen to push service (WebSocket, long-polling AJAX, etc.) so if some event happen on server, the server will notify clients about it.

Consider say SockJS or Socket.IO for own implementation or some push service in the cloud that provides an API for these purposes, eg Pusher .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM