##// END OF EJS Templates
Added code that removes the views when a model/widget is closed.
Jonathan Frederic -
Show More
@@ -1,411 +1,413
1 //----------------------------------------------------------------------------
1 //----------------------------------------------------------------------------
2 // Copyright (C) 2013 The IPython Development Team
2 // Copyright (C) 2013 The IPython Development Team
3 //
3 //
4 // Distributed under the terms of the BSD License. The full license is in
4 // Distributed under the terms of the BSD License. The full license is in
5 // the file COPYING, distributed as part of this software.
5 // the file COPYING, distributed as part of this software.
6 //----------------------------------------------------------------------------
6 //----------------------------------------------------------------------------
7
7
8 //============================================================================
8 //============================================================================
9 // Base Widget Model and View classes
9 // Base Widget Model and View classes
10 //============================================================================
10 //============================================================================
11
11
12 /**
12 /**
13 * @module IPython
13 * @module IPython
14 * @namespace IPython
14 * @namespace IPython
15 **/
15 **/
16
16
17 define(["notebook/js/widgetmanager",
17 define(["notebook/js/widgetmanager",
18 "underscore",
18 "underscore",
19 "backbone"],
19 "backbone"],
20 function(WidgetManager, Underscore, Backbone){
20 function(WidgetManager, Underscore, Backbone){
21
21
22 var WidgetModel = Backbone.Model.extend({
22 var WidgetModel = Backbone.Model.extend({
23 constructor: function (widget_manager, model_id, comm) {
23 constructor: function (widget_manager, model_id, comm) {
24 // Construcctor
24 // Construcctor
25 //
25 //
26 // Creates a WidgetModel instance.
26 // Creates a WidgetModel instance.
27 //
27 //
28 // Parameters
28 // Parameters
29 // ----------
29 // ----------
30 // widget_manager : WidgetManager instance
30 // widget_manager : WidgetManager instance
31 // model_id : string
31 // model_id : string
32 // An ID unique to this model.
32 // An ID unique to this model.
33 // comm : Comm instance (optional)
33 // comm : Comm instance (optional)
34 this.widget_manager = widget_manager;
34 this.widget_manager = widget_manager;
35 this.pending_msgs = 0;
35 this.pending_msgs = 0;
36 this.msg_throttle = 3;
36 this.msg_throttle = 3;
37 this.msg_buffer = null;
37 this.msg_buffer = null;
38 this.key_value_lock = null;
38 this.key_value_lock = null;
39 this.id = model_id;
39 this.id = model_id;
40 this.views = [];
40 this.views = [];
41
41
42 if (comm !== undefined) {
42 if (comm !== undefined) {
43 // Remember comm associated with the model.
43 // Remember comm associated with the model.
44 this.comm = comm;
44 this.comm = comm;
45 comm.model = this;
45 comm.model = this;
46
46
47 // Hook comm messages up to model.
47 // Hook comm messages up to model.
48 comm.on_close($.proxy(this._handle_comm_closed, this));
48 comm.on_close($.proxy(this._handle_comm_closed, this));
49 comm.on_msg($.proxy(this._handle_comm_msg, this));
49 comm.on_msg($.proxy(this._handle_comm_msg, this));
50 }
50 }
51 return Backbone.Model.apply(this);
51 return Backbone.Model.apply(this);
52 },
52 },
53
53
54 send: function (content, callbacks) {
54 send: function (content, callbacks) {
55 // Send a custom msg over the comm.
55 // Send a custom msg over the comm.
56 if (this.comm !== undefined) {
56 if (this.comm !== undefined) {
57 var data = {method: 'custom', content: content};
57 var data = {method: 'custom', content: content};
58 this.comm.send(data, callbacks);
58 this.comm.send(data, callbacks);
59 }
59 }
60 },
60 },
61
61
62 _handle_comm_closed: function (msg) {
62 _handle_comm_closed: function (msg) {
63 // Handle when a widget is closed.
63 // Handle when a widget is closed.
64 this.trigger('comm:close');
64 this.trigger('comm:close');
65 delete this.comm.model; // Delete ref so GC will collect widget model.
65 delete this.comm.model; // Delete ref so GC will collect widget model.
66 delete this.comm;
66 delete this.comm;
67 delete this.model_id; // Delete id from model so widget manager cleans up.
67 delete this.model_id; // Delete id from model so widget manager cleans up.
68 // TODO: Handle deletion, like this.destroy(), and delete views, etc.
68 _.each(this.views, function(view, i) {
69 view.remove();
70 });
69 },
71 },
70
72
71 _handle_comm_msg: function (msg) {
73 _handle_comm_msg: function (msg) {
72 // Handle incoming comm msg.
74 // Handle incoming comm msg.
73 var method = msg.content.data.method;
75 var method = msg.content.data.method;
74 switch (method) {
76 switch (method) {
75 case 'update':
77 case 'update':
76 this.apply_update(msg.content.data.state);
78 this.apply_update(msg.content.data.state);
77 break;
79 break;
78 case 'custom':
80 case 'custom':
79 this.trigger('msg:custom', msg.content.data.content);
81 this.trigger('msg:custom', msg.content.data.content);
80 break;
82 break;
81 case 'display':
83 case 'display':
82 this.widget_manager.display_view(msg, this);
84 this.widget_manager.display_view(msg, this);
83 break;
85 break;
84 }
86 }
85 },
87 },
86
88
87 apply_update: function (state) {
89 apply_update: function (state) {
88 // Handle when a widget is updated via the python side.
90 // Handle when a widget is updated via the python side.
89 var that = this;
91 var that = this;
90 _.each(state, function(value, key) {
92 _.each(state, function(value, key) {
91 that.key_value_lock = [key, value];
93 that.key_value_lock = [key, value];
92 try {
94 try {
93 that.set(key, that._unpack_models(value));
95 that.set(key, that._unpack_models(value));
94 } finally {
96 } finally {
95 that.key_value_lock = null;
97 that.key_value_lock = null;
96 }
98 }
97 });
99 });
98 },
100 },
99
101
100 _handle_status: function (msg, callbacks) {
102 _handle_status: function (msg, callbacks) {
101 // Handle status msgs.
103 // Handle status msgs.
102
104
103 // execution_state : ('busy', 'idle', 'starting')
105 // execution_state : ('busy', 'idle', 'starting')
104 if (this.comm !== undefined) {
106 if (this.comm !== undefined) {
105 if (msg.content.execution_state ==='idle') {
107 if (msg.content.execution_state ==='idle') {
106 // Send buffer if this message caused another message to be
108 // Send buffer if this message caused another message to be
107 // throttled.
109 // throttled.
108 if (this.msg_buffer !== null &&
110 if (this.msg_buffer !== null &&
109 this.msg_throttle === this.pending_msgs) {
111 this.msg_throttle === this.pending_msgs) {
110 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
112 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
111 this.comm.send(data, callbacks);
113 this.comm.send(data, callbacks);
112 this.msg_buffer = null;
114 this.msg_buffer = null;
113 } else {
115 } else {
114 --this.pending_msgs;
116 --this.pending_msgs;
115 }
117 }
116 }
118 }
117 }
119 }
118 },
120 },
119
121
120 callbacks: function(view) {
122 callbacks: function(view) {
121 // Create msg callbacks for a comm msg.
123 // Create msg callbacks for a comm msg.
122 var callbacks = this.widget_manager.callbacks(view);
124 var callbacks = this.widget_manager.callbacks(view);
123
125
124 if (callbacks.iopub === undefined) {
126 if (callbacks.iopub === undefined) {
125 callbacks.iopub = {};
127 callbacks.iopub = {};
126 }
128 }
127
129
128 var that = this;
130 var that = this;
129 callbacks.iopub.status = function (msg) {
131 callbacks.iopub.status = function (msg) {
130 that._handle_status(msg, callbacks);
132 that._handle_status(msg, callbacks);
131 }
133 }
132 return callbacks;
134 return callbacks;
133 },
135 },
134
136
135 sync: function (method, model, options) {
137 sync: function (method, model, options) {
136 // Handle sync to the back-end. Called when a model.save() is called.
138 // Handle sync to the back-end. Called when a model.save() is called.
137
139
138 // Make sure a comm exists.
140 // Make sure a comm exists.
139 var error = options.error || function() {
141 var error = options.error || function() {
140 console.error('Backbone sync error:', arguments);
142 console.error('Backbone sync error:', arguments);
141 }
143 }
142 if (this.comm === undefined) {
144 if (this.comm === undefined) {
143 error();
145 error();
144 return false;
146 return false;
145 }
147 }
146
148
147 // Delete any key value pairs that the back-end already knows about.
149 // Delete any key value pairs that the back-end already knows about.
148 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
150 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
149 if (this.key_value_lock !== null) {
151 if (this.key_value_lock !== null) {
150 var key = this.key_value_lock[0];
152 var key = this.key_value_lock[0];
151 var value = this.key_value_lock[1];
153 var value = this.key_value_lock[1];
152 if (attrs[key] === value) {
154 if (attrs[key] === value) {
153 delete attrs[key];
155 delete attrs[key];
154 }
156 }
155 }
157 }
156
158
157 // Only sync if there are attributes to send to the back-end.
159 // Only sync if there are attributes to send to the back-end.
158 if (_.size(attrs) > 0) {
160 if (_.size(attrs) > 0) {
159 var callbacks = options.callbacks || {};
161 var callbacks = options.callbacks || {};
160 if (this.pending_msgs >= this.msg_throttle) {
162 if (this.pending_msgs >= this.msg_throttle) {
161 // The throttle has been exceeded, buffer the current msg so
163 // The throttle has been exceeded, buffer the current msg so
162 // it can be sent once the kernel has finished processing
164 // it can be sent once the kernel has finished processing
163 // some of the existing messages.
165 // some of the existing messages.
164
166
165 // Combine updates if it is a 'patch' sync, otherwise replace updates
167 // Combine updates if it is a 'patch' sync, otherwise replace updates
166 switch (method) {
168 switch (method) {
167 case 'patch':
169 case 'patch':
168 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
170 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
169 break;
171 break;
170 case 'update':
172 case 'update':
171 case 'create':
173 case 'create':
172 this.msg_buffer = attrs;
174 this.msg_buffer = attrs;
173 break;
175 break;
174 default:
176 default:
175 error();
177 error();
176 return false;
178 return false;
177 }
179 }
178 this.msg_buffer_callbacks = callbacks;
180 this.msg_buffer_callbacks = callbacks;
179
181
180 } else {
182 } else {
181 // We haven't exceeded the throttle, send the message like
183 // We haven't exceeded the throttle, send the message like
182 // normal. If this is a patch operation, just send the
184 // normal. If this is a patch operation, just send the
183 // changes.
185 // changes.
184 var data = {method: 'backbone', sync_data: attrs};
186 var data = {method: 'backbone', sync_data: attrs};
185 this.comm.send(data, callbacks);
187 this.comm.send(data, callbacks);
186 this.pending_msgs++;
188 this.pending_msgs++;
187 }
189 }
188 }
190 }
189 // Since the comm is a one-way communication, assume the message
191 // Since the comm is a one-way communication, assume the message
190 // arrived. Don't call success since we don't have a model back from the server
192 // arrived. Don't call success since we don't have a model back from the server
191 // this means we miss out on the 'sync' event.
193 // this means we miss out on the 'sync' event.
192 },
194 },
193
195
194 save_changes: function(callbacks) {
196 save_changes: function(callbacks) {
195 // Push this model's state to the back-end
197 // Push this model's state to the back-end
196 //
198 //
197 // This invokes a Backbone.Sync.
199 // This invokes a Backbone.Sync.
198 this.save(this.changedAttributes(), {patch: true, callbacks: callbacks});
200 this.save(this.changedAttributes(), {patch: true, callbacks: callbacks});
199 },
201 },
200
202
201 _pack_models: function(value) {
203 _pack_models: function(value) {
202 // Replace models with model ids recursively.
204 // Replace models with model ids recursively.
203 if (value instanceof Backbone.Model) {
205 if (value instanceof Backbone.Model) {
204 return value.id;
206 return value.id;
205 } else if (value instanceof Object) {
207 } else if (value instanceof Object) {
206 var packed = {};
208 var packed = {};
207 var that = this;
209 var that = this;
208 _.each(value, function(sub_value, key) {
210 _.each(value, function(sub_value, key) {
209 packed[key] = that._pack_models(sub_value);
211 packed[key] = that._pack_models(sub_value);
210 });
212 });
211 return packed;
213 return packed;
212 } else {
214 } else {
213 return value;
215 return value;
214 }
216 }
215 },
217 },
216
218
217 _unpack_models: function(value) {
219 _unpack_models: function(value) {
218 // Replace model ids with models recursively.
220 // Replace model ids with models recursively.
219 if (value instanceof Object) {
221 if (value instanceof Object) {
220 var unpacked = {};
222 var unpacked = {};
221 var that = this;
223 var that = this;
222 _.each(value, function(sub_value, key) {
224 _.each(value, function(sub_value, key) {
223 unpacked[key] = that._unpack_models(sub_value);
225 unpacked[key] = that._unpack_models(sub_value);
224 });
226 });
225 return unpacked;
227 return unpacked;
226 } else {
228 } else {
227 var model = this.widget_manager.get_model(value);
229 var model = this.widget_manager.get_model(value);
228 if (model !== null) {
230 if (model !== null) {
229 return model;
231 return model;
230 } else {
232 } else {
231 return value;
233 return value;
232 }
234 }
233 }
235 }
234 },
236 },
235
237
236 });
238 });
237 WidgetManager.register_widget_model('WidgetModel', WidgetModel);
239 WidgetManager.register_widget_model('WidgetModel', WidgetModel);
238
240
239
241
240 var WidgetView = Backbone.View.extend({
242 var WidgetView = Backbone.View.extend({
241 initialize: function(parameters) {
243 initialize: function(parameters) {
242 // Public constructor.
244 // Public constructor.
243 this.model.on('change',this.update,this);
245 this.model.on('change',this.update,this);
244 this.options = parameters.options;
246 this.options = parameters.options;
245 this.child_views = [];
247 this.child_views = [];
246 this.model.views.push(this);
248 this.model.views.push(this);
247 },
249 },
248
250
249 update: function(){
251 update: function(){
250 // Triggered on model change.
252 // Triggered on model change.
251 //
253 //
252 // Update view to be consistent with this.model
254 // Update view to be consistent with this.model
253 },
255 },
254
256
255 create_child_view: function(child_model, options) {
257 create_child_view: function(child_model, options) {
256 // Create and return a child view.
258 // Create and return a child view.
257 //
259 //
258 // -given a model and (optionally) a view name if the view name is
260 // -given a model and (optionally) a view name if the view name is
259 // not given, it defaults to the model's default view attribute.
261 // not given, it defaults to the model's default view attribute.
260
262
261 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
263 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
262 // it would be great to have the widget manager add the cell metadata
264 // it would be great to have the widget manager add the cell metadata
263 // to the subview without having to add it here.
265 // to the subview without having to add it here.
264 var child_view = this.model.widget_manager.create_view(child_model, options || {}, this);
266 var child_view = this.model.widget_manager.create_view(child_model, options || {}, this);
265 this.child_views[child_model.id] = child_view;
267 this.child_views[child_model.id] = child_view;
266 return child_view;
268 return child_view;
267 },
269 },
268
270
269 delete_child_view: function(child_model, options) {
271 delete_child_view: function(child_model, options) {
270 // Delete a child view that was previously created using create_child_view.
272 // Delete a child view that was previously created using create_child_view.
271 var view = this.child_views[child_model.id];
273 var view = this.child_views[child_model.id];
272 if (view !== undefined) {
274 if (view !== undefined) {
273 delete this.child_views[child_model.id];
275 delete this.child_views[child_model.id];
274 view.remove();
276 view.remove();
275 }
277 }
276 },
278 },
277
279
278 do_diff: function(old_list, new_list, removed_callback, added_callback) {
280 do_diff: function(old_list, new_list, removed_callback, added_callback) {
279 // Difference a changed list and call remove and add callbacks for
281 // Difference a changed list and call remove and add callbacks for
280 // each removed and added item in the new list.
282 // each removed and added item in the new list.
281 //
283 //
282 // Parameters
284 // Parameters
283 // ----------
285 // ----------
284 // old_list : array
286 // old_list : array
285 // new_list : array
287 // new_list : array
286 // removed_callback : Callback(item)
288 // removed_callback : Callback(item)
287 // Callback that is called for each item removed.
289 // Callback that is called for each item removed.
288 // added_callback : Callback(item)
290 // added_callback : Callback(item)
289 // Callback that is called for each item added.
291 // Callback that is called for each item added.
290
292
291
293
292 // removed items
294 // removed items
293 _.each(_.difference(old_list, new_list), function(item, index, list) {
295 _.each(_.difference(old_list, new_list), function(item, index, list) {
294 removed_callback(item);
296 removed_callback(item);
295 }, this);
297 }, this);
296
298
297 // added items
299 // added items
298 _.each(_.difference(new_list, old_list), function(item, index, list) {
300 _.each(_.difference(new_list, old_list), function(item, index, list) {
299 added_callback(item);
301 added_callback(item);
300 }, this);
302 }, this);
301 },
303 },
302
304
303 callbacks: function(){
305 callbacks: function(){
304 // Create msg callbacks for a comm msg.
306 // Create msg callbacks for a comm msg.
305 return this.model.callbacks(this);
307 return this.model.callbacks(this);
306 },
308 },
307
309
308 render: function(){
310 render: function(){
309 // Render the view.
311 // Render the view.
310 //
312 //
311 // By default, this is only called the first time the view is created
313 // By default, this is only called the first time the view is created
312 },
314 },
313
315
314 send: function (content) {
316 send: function (content) {
315 // Send a custom msg associated with this view.
317 // Send a custom msg associated with this view.
316 this.model.send(content, this.callbacks());
318 this.model.send(content, this.callbacks());
317 },
319 },
318
320
319 touch: function () {
321 touch: function () {
320 this.model.save_changes(this.callbacks());
322 this.model.save_changes(this.callbacks());
321 },
323 },
322 });
324 });
323
325
324
326
325 var DOMWidgetView = WidgetView.extend({
327 var DOMWidgetView = WidgetView.extend({
326 initialize: function (options) {
328 initialize: function (options) {
327 // Public constructor
329 // Public constructor
328
330
329 // In the future we may want to make changes more granular
331 // In the future we may want to make changes more granular
330 // (e.g., trigger on visible:change).
332 // (e.g., trigger on visible:change).
331 this.model.on('change', this.update, this);
333 this.model.on('change', this.update, this);
332 this.model.on('msg:custom', this.on_msg, this);
334 this.model.on('msg:custom', this.on_msg, this);
333 DOMWidgetView.__super__.initialize.apply(this, arguments);
335 DOMWidgetView.__super__.initialize.apply(this, arguments);
334 },
336 },
335
337
336 on_msg: function(msg) {
338 on_msg: function(msg) {
337 // Handle DOM specific msgs.
339 // Handle DOM specific msgs.
338 switch(msg.msg_type) {
340 switch(msg.msg_type) {
339 case 'add_class':
341 case 'add_class':
340 this.add_class(msg.selector, msg.class_list);
342 this.add_class(msg.selector, msg.class_list);
341 break;
343 break;
342 case 'remove_class':
344 case 'remove_class':
343 this.remove_class(msg.selector, msg.class_list);
345 this.remove_class(msg.selector, msg.class_list);
344 break;
346 break;
345 }
347 }
346 },
348 },
347
349
348 add_class: function (selector, class_list) {
350 add_class: function (selector, class_list) {
349 // Add a DOM class to an element.
351 // Add a DOM class to an element.
350 this._get_selector_element(selector).addClass(class_list);
352 this._get_selector_element(selector).addClass(class_list);
351 },
353 },
352
354
353 remove_class: function (selector, class_list) {
355 remove_class: function (selector, class_list) {
354 // Remove a DOM class from an element.
356 // Remove a DOM class from an element.
355 this._get_selector_element(selector).removeClass(class_list);
357 this._get_selector_element(selector).removeClass(class_list);
356 },
358 },
357
359
358 update: function () {
360 update: function () {
359 // Update the contents of this view
361 // Update the contents of this view
360 //
362 //
361 // Called when the model is changed. The model may have been
363 // Called when the model is changed. The model may have been
362 // changed by another view or by a state update from the back-end.
364 // changed by another view or by a state update from the back-end.
363 // The very first update seems to happen before the element is
365 // The very first update seems to happen before the element is
364 // finished rendering so we use setTimeout to give the element time
366 // finished rendering so we use setTimeout to give the element time
365 // to render
367 // to render
366 var e = this.$el;
368 var e = this.$el;
367 var visible = this.model.get('visible');
369 var visible = this.model.get('visible');
368 setTimeout(function() {e.toggle(visible)},0);
370 setTimeout(function() {e.toggle(visible)},0);
369
371
370 var css = this.model.get('_css');
372 var css = this.model.get('_css');
371 if (css === undefined) {return;}
373 if (css === undefined) {return;}
372 var that = this;
374 var that = this;
373 _.each(css, function(css_traits, selector){
375 _.each(css, function(css_traits, selector){
374 // Apply the css traits to all elements that match the selector.
376 // Apply the css traits to all elements that match the selector.
375 var elements = that._get_selector_element(selector);
377 var elements = that._get_selector_element(selector);
376 if (elements.length > 0) {
378 if (elements.length > 0) {
377 _.each(css_traits, function(css_value, css_key){
379 _.each(css_traits, function(css_value, css_key){
378 elements.css(css_key, css_value);
380 elements.css(css_key, css_value);
379 });
381 });
380 }
382 }
381 });
383 });
382
384
383 },
385 },
384
386
385 _get_selector_element: function (selector) {
387 _get_selector_element: function (selector) {
386 // Get the elements via the css selector.
388 // Get the elements via the css selector.
387
389
388 // If the selector is blank, apply the style to the $el_to_style
390 // If the selector is blank, apply the style to the $el_to_style
389 // element. If the $el_to_style element is not defined, use apply
391 // element. If the $el_to_style element is not defined, use apply
390 // the style to the view's element.
392 // the style to the view's element.
391 var elements;
393 var elements;
392 if (selector === undefined || selector === null || selector === '') {
394 if (selector === undefined || selector === null || selector === '') {
393 if (this.$el_to_style === undefined) {
395 if (this.$el_to_style === undefined) {
394 elements = this.$el;
396 elements = this.$el;
395 } else {
397 } else {
396 elements = this.$el_to_style;
398 elements = this.$el_to_style;
397 }
399 }
398 } else {
400 } else {
399 elements = this.$el.find(selector);
401 elements = this.$el.find(selector);
400 }
402 }
401 return elements;
403 return elements;
402 },
404 },
403 });
405 });
404
406
405 IPython.WidgetModel = WidgetModel;
407 IPython.WidgetModel = WidgetModel;
406 IPython.WidgetView = WidgetView;
408 IPython.WidgetView = WidgetView;
407 IPython.DOMWidgetView = DOMWidgetView;
409 IPython.DOMWidgetView = DOMWidgetView;
408
410
409 // Pass through WidgetManager namespace.
411 // Pass through WidgetManager namespace.
410 return WidgetManager;
412 return WidgetManager;
411 });
413 });
General Comments 0
You need to be logged in to leave comments. Login now