1 | define(['../Evented', '../_base/lang', './util'], function(Evented, lang, util){ |
---|
2 | // module: |
---|
3 | // dojo/request/notify |
---|
4 | // summary: |
---|
5 | // Global notification API for dojo/request. Notifications will |
---|
6 | // only be emitted if this module is required. |
---|
7 | // |
---|
8 | // | require('dojo/request', 'dojo/request/notify', |
---|
9 | // | function(request, notify){ |
---|
10 | // | notify('load', function(response){ |
---|
11 | // | if(response.url === 'someUrl.html'){ |
---|
12 | // | console.log('Loaded!'); |
---|
13 | // | } |
---|
14 | // | }); |
---|
15 | // | request.get('someUrl.html'); |
---|
16 | // | } |
---|
17 | // | ); |
---|
18 | |
---|
19 | var pubCount = 0, |
---|
20 | slice = [].slice; |
---|
21 | |
---|
22 | var hub = lang.mixin(new Evented, { |
---|
23 | onsend: function(data){ |
---|
24 | if(!pubCount){ |
---|
25 | this.emit('start'); |
---|
26 | } |
---|
27 | pubCount++; |
---|
28 | }, |
---|
29 | _onload: function(data){ |
---|
30 | this.emit('done', data); |
---|
31 | }, |
---|
32 | _onerror: function(data){ |
---|
33 | this.emit('done', data); |
---|
34 | }, |
---|
35 | _ondone: function(data){ |
---|
36 | if(--pubCount <= 0){ |
---|
37 | pubCount = 0; |
---|
38 | this.emit('stop'); |
---|
39 | } |
---|
40 | }, |
---|
41 | emit: function(type, event){ |
---|
42 | var result = Evented.prototype.emit.apply(this, arguments); |
---|
43 | |
---|
44 | // After all event handlers have run, run _on* handler |
---|
45 | if(this['_on' + type]){ |
---|
46 | this['_on' + type].apply(this, slice.call(arguments, 1)); |
---|
47 | } |
---|
48 | return result; |
---|
49 | } |
---|
50 | }); |
---|
51 | |
---|
52 | function notify(type, listener){ |
---|
53 | // summary: |
---|
54 | // Register a listener to be notified when an event |
---|
55 | // in dojo/request happens. |
---|
56 | // type: String? |
---|
57 | // The event to listen for. Events emitted: "start", "send", |
---|
58 | // "load", "error", "done", "stop". |
---|
59 | // listener: Function? |
---|
60 | // A callback to be run when an event happens. |
---|
61 | // returns: |
---|
62 | // A signal object that can be used to cancel the listener. |
---|
63 | // If remove() is called on this signal object, it will |
---|
64 | // stop the listener from being executed. |
---|
65 | return hub.on(type, listener); |
---|
66 | } |
---|
67 | notify.emit = function(type, event, cancel){ |
---|
68 | return hub.emit(type, event, cancel); |
---|
69 | }; |
---|
70 | |
---|
71 | // Attach notify to dojo/request/util to avoid |
---|
72 | // try{ require('./notify'); }catch(e){} |
---|
73 | return util.notify = notify; |
---|
74 | }); |
---|