UNPKG

2.58 kBJavaScriptView Raw
1// Generated by CoffeeScript 1.10.0
2
3/*
4 *
5 * Listen 'fetched', 'onFetched'
6 * Listen 'fetched', -> log 'model fetched'
7 *
8 */
9var Listen, ensurePromise,
10 slice = [].slice;
11
12ensurePromise = require('./utils').ensurePromise;
13
14Listen = (function() {
15 function Listen() {
16 var callbacks, event;
17 event = arguments[0], callbacks = 2 <= arguments.length ? slice.call(arguments, 1) : [];
18 if (!(this instanceof Listen)) {
19 return (function(func, args, ctor) {
20 ctor.prototype = func.prototype;
21 var child = new ctor, result = func.apply(child, args);
22 return Object(result) === result ? result : child;
23 })(Listen, [event].concat(slice.call(callbacks)), function(){});
24 }
25 this.event = event;
26 if (typeof callbacks[callbacks.length - 1] === 'object') {
27 this.options = callbacks.pop();
28 } else {
29 this.options = {};
30 }
31 this.callbacks = callbacks;
32 }
33
34 Listen.prototype.contributeToSchema = function(schema) {
35 return schema.push(this);
36 };
37
38 Listen.prototype.contributeToModel = function() {};
39
40 Listen.prototype.initialize = function(instance) {
41 var c, condition, fns, listener;
42 fns = (function() {
43 var i, len, ref, results;
44 ref = this.callbacks;
45 results = [];
46 for (i = 0, len = ref.length; i < len; i++) {
47 c = ref[i];
48 results.push(this._bindCallback(c, instance));
49 }
50 return results;
51 }).call(this);
52 listener = this.options.condition ? (condition = this._bindCallback(this.options.condition, instance), function() {
53 var args;
54 args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
55 return ensurePromise(condition.apply(null, args)).then(function(result) {
56 var f, i, len, results;
57 if (result) {
58 results = [];
59 for (i = 0, len = fns.length; i < len; i++) {
60 f = fns[i];
61 results.push(f.apply(null, args));
62 }
63 return results;
64 }
65 });
66 }) : function() {
67 var args, f, i, len, results;
68 args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
69 results = [];
70 for (i = 0, len = fns.length; i < len; i++) {
71 f = fns[i];
72 results.push(f.apply(null, args));
73 }
74 return results;
75 };
76 return instance.on(this.event, listener);
77 };
78
79 Listen.prototype._bindCallback = function(c, instance) {
80 if (typeof c === 'string') {
81 return instance[c].bind(instance);
82 } else {
83 return c.bind(instance);
84 }
85 };
86
87 return Listen;
88
89})();
90
91module.exports = Listen;