-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathController.js
94 lines (80 loc) · 2.24 KB
/
Controller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* istanbul ignore if */
if (typeof define !== 'function') { var define = require('amdefine')(module); }
define([
'./util/construct',
'./Class',
'./View',
'./Model',
'./Promise',
'./trait/pubsub'
], function(construct, Class, View, Model, Promise, pubsub) {
'use strict';
var constructor = Class.extend({
init: function() {
this._initModel.apply(this, arguments);
this.requestView();
},
render: function($parent, ViewClass) {
this.requestView(ViewClass);
return new Promise(function(resolve) {
resolve(this._view.render($parent));
}.bind(this));
},
destroy: function() {
if (this._view) { this._view.destroy(); }
this._model.destroy();
this._model = this._view = null;
this.trigger('destroy').stopListening().off();
},
_initModel: function() {
var ModelClass = this.Model || this.constructor.MODEL_CLASS;
this._model = construct.apply(ModelClass, arguments);
},
_initView: function() {
var ViewClass = Array.prototype.shift.call(arguments);
this._view = construct.apply(ViewClass, arguments);
this._view._controller = this;
},
switchView: function() {
var existing = this._view;
this._initView.apply(this, arguments);
if (!existing) { return; }
if (existing.$view) {
this._view.$view = existing.$view;
this._view.render();
}
if (existing.destroy) {
existing.destroy();
}
},
requestView: function(ViewClass) {
ViewClass = ViewClass || this.View || this.constructor.VIEW_CLASS;
if (typeof ViewClass === 'string') {
ViewClass = this.constructor.VIEW_CLASS[ViewClass];
}
if (typeof ViewClass !== 'function' || this._view instanceof ViewClass) {
return;
}
this.switchView(ViewClass, this._model);
},
toJSON: function() {
return this._model.toJSON();
}
}, {
displayName: 'Controller',
// Corresponding Entity View class
VIEW_CLASS: View,
// Corresponding Entity Model class
MODEL_CLASS: Model
})
.mixin(pubsub)
.mixin({
get id() {
return this._model.id();
},
get data() {
return this._model.data();
}
});
return constructor;
});