##// END OF EJS Templates
Save changes should only save if comm is live
Sylvain Corlay -
Show More
@@ -1,763 +1,765 b''
1 1 // Copyright (c) IPython Development Team.
2 2 // Distributed under the terms of the Modified BSD License.
3 3
4 4 define(["widgets/js/manager",
5 5 "underscore",
6 6 "backbone",
7 7 "jquery",
8 8 "base/js/utils",
9 9 "base/js/namespace",
10 10 ], function(widgetmanager, _, Backbone, $, utils, IPython){
11 11 "use strict";
12 12
13 13 var WidgetModel = Backbone.Model.extend({
14 14 constructor: function (widget_manager, model_id, comm) {
15 15 /**
16 16 * Constructor
17 17 *
18 18 * Creates a WidgetModel instance.
19 19 *
20 20 * Parameters
21 21 * ----------
22 22 * widget_manager : WidgetManager instance
23 23 * model_id : string
24 24 * An ID unique to this model.
25 25 * comm : Comm instance (optional)
26 26 */
27 27 this.widget_manager = widget_manager;
28 28 this.state_change = Promise.resolve();
29 29 this._buffered_state_diff = {};
30 30 this.pending_msgs = 0;
31 31 this.msg_buffer = null;
32 32 this.state_lock = null;
33 33 this.id = model_id;
34 34 this.views = {};
35 35 this._resolve_received_state = {};
36 36
37 37 if (comm !== undefined) {
38 38 // Remember comm associated with the model.
39 39 this.comm = comm;
40 40 comm.model = this;
41 41
42 42 // Hook comm messages up to model.
43 43 comm.on_close($.proxy(this._handle_comm_closed, this));
44 44 comm.on_msg($.proxy(this._handle_comm_msg, this));
45 45
46 46 // Assume the comm is alive.
47 47 this.set_comm_live(true);
48 48 } else {
49 49 this.set_comm_live(false);
50 50 }
51 51
52 52 // Listen for the events that lead to the websocket being terminated.
53 53 var that = this;
54 54 var died = function() {
55 55 that.set_comm_live(false);
56 56 };
57 57 widget_manager.notebook.events.on('kernel_disconnected.Kernel', died);
58 58 widget_manager.notebook.events.on('kernel_killed.Kernel', died);
59 59 widget_manager.notebook.events.on('kernel_restarting.Kernel', died);
60 60 widget_manager.notebook.events.on('kernel_dead.Kernel', died);
61 61
62 62 return Backbone.Model.apply(this);
63 63 },
64 64
65 65 send: function (content, callbacks) {
66 66 /**
67 67 * Send a custom msg over the comm.
68 68 */
69 69 if (this.comm !== undefined) {
70 70 var data = {method: 'custom', content: content};
71 71 this.comm.send(data, callbacks);
72 72 this.pending_msgs++;
73 73 }
74 74 },
75 75
76 76 request_state: function(callbacks) {
77 77 /**
78 78 * Request a state push from the back-end.
79 79 */
80 80 if (!this.comm) {
81 81 console.error("Could not request_state because comm doesn't exist!");
82 82 return;
83 83 }
84 84
85 85 var msg_id = this.comm.send({method: 'request_state'}, callbacks || this.widget_manager.callbacks());
86 86
87 87 // Promise that is resolved when a state is received
88 88 // from the back-end.
89 89 var that = this;
90 90 var received_state = new Promise(function(resolve) {
91 91 that._resolve_received_state[msg_id] = resolve;
92 92 });
93 93 return received_state;
94 94 },
95 95
96 96 set_comm_live: function(live) {
97 97 /**
98 98 * Change the comm_live state of the model.
99 99 */
100 100 if (this.comm_live === undefined || this.comm_live != live) {
101 101 this.comm_live = live;
102 102 this.trigger(live ? 'comm:live' : 'comm:dead', {model: this});
103 103 }
104 104 },
105 105
106 106 close: function(comm_closed) {
107 107 /**
108 108 * Close model
109 109 */
110 110 if (this.comm && !comm_closed) {
111 111 this.comm.close();
112 112 }
113 113 this.stopListening();
114 114 this.trigger('destroy', this);
115 115 delete this.comm.model; // Delete ref so GC will collect widget model.
116 116 delete this.comm;
117 117 delete this.model_id; // Delete id from model so widget manager cleans up.
118 118 _.each(this.views, function(v, id, views) {
119 119 v.then(function(view) {
120 120 view.remove();
121 121 delete views[id];
122 122 });
123 123 });
124 124 },
125 125
126 126 _handle_comm_closed: function (msg) {
127 127 /**
128 128 * Handle when a widget is closed.
129 129 */
130 130 this.trigger('comm:close');
131 131 this.close(true);
132 132 },
133 133
134 134 _handle_comm_msg: function (msg) {
135 135 /**
136 136 * Handle incoming comm msg.
137 137 */
138 138 var method = msg.content.data.method;
139 139 var that = this;
140 140 switch (method) {
141 141 case 'update':
142 142 this.state_change = this.state_change
143 143 .then(function() {
144 144 return that.set_state(msg.content.data.state);
145 145 }).catch(utils.reject("Couldn't process update msg for model id '" + String(that.id) + "'", true))
146 146 .then(function() {
147 147 var parent_id = msg.parent_header.msg_id;
148 148 if (that._resolve_received_state[parent_id] !== undefined) {
149 149 that._resolve_received_state[parent_id].call();
150 150 delete that._resolve_received_state[parent_id];
151 151 }
152 152 }).catch(utils.reject("Couldn't resolve state request promise", true));
153 153 break;
154 154 case 'custom':
155 155 this.trigger('msg:custom', msg.content.data.content);
156 156 break;
157 157 case 'display':
158 158 this.state_change = this.state_change.then(function() {
159 159 that.widget_manager.display_view(msg, that);
160 160 }).catch(utils.reject('Could not process display view msg', true));
161 161 break;
162 162 }
163 163 },
164 164
165 165 set_state: function (state) {
166 166 var that = this;
167 167 // Handle when a widget is updated via the python side.
168 168 return this._unpack_models(state).then(function(state) {
169 169 that.state_lock = state;
170 170 try {
171 171 WidgetModel.__super__.set.call(that, state);
172 172 } finally {
173 173 that.state_lock = null;
174 174 }
175 175 }).catch(utils.reject("Couldn't set model state", true));
176 176 },
177 177
178 178 get_state: function() {
179 179 // Get the serializable state of the model.
180 180 var state = this.toJSON();
181 181 for (var key in state) {
182 182 if (state.hasOwnProperty(key)) {
183 183 state[key] = this._pack_models(state[key]);
184 184 }
185 185 }
186 186 return state;
187 187 },
188 188
189 189 _handle_status: function (msg, callbacks) {
190 190 /**
191 191 * Handle status msgs.
192 192 *
193 193 * execution_state : ('busy', 'idle', 'starting')
194 194 */
195 195 if (this.comm !== undefined) {
196 196 if (msg.content.execution_state ==='idle') {
197 197 // Send buffer if this message caused another message to be
198 198 // throttled.
199 199 if (this.msg_buffer !== null &&
200 200 (this.get('msg_throttle') || 3) === this.pending_msgs) {
201 201 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
202 202 this.comm.send(data, callbacks);
203 203 this.msg_buffer = null;
204 204 } else {
205 205 --this.pending_msgs;
206 206 }
207 207 }
208 208 }
209 209 },
210 210
211 211 callbacks: function(view) {
212 212 /**
213 213 * Create msg callbacks for a comm msg.
214 214 */
215 215 var callbacks = this.widget_manager.callbacks(view);
216 216
217 217 if (callbacks.iopub === undefined) {
218 218 callbacks.iopub = {};
219 219 }
220 220
221 221 var that = this;
222 222 callbacks.iopub.status = function (msg) {
223 223 that._handle_status(msg, callbacks);
224 224 };
225 225 return callbacks;
226 226 },
227 227
228 228 set: function(key, val, options) {
229 229 /**
230 230 * Set a value.
231 231 */
232 232 var return_value = WidgetModel.__super__.set.apply(this, arguments);
233 233
234 234 // Backbone only remembers the diff of the most recent set()
235 235 // operation. Calling set multiple times in a row results in a
236 236 // loss of diff information. Here we keep our own running diff.
237 237 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
238 238 return return_value;
239 239 },
240 240
241 241 sync: function (method, model, options) {
242 242 /**
243 243 * Handle sync to the back-end. Called when a model.save() is called.
244 244 *
245 245 * Make sure a comm exists.
246 246 */
247 247 var error = options.error || function() {
248 248 console.error('Backbone sync error:', arguments);
249 249 };
250 250 if (this.comm === undefined) {
251 251 error();
252 252 return false;
253 253 }
254 254
255 255 // Delete any key value pairs that the back-end already knows about.
256 256 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
257 257 if (this.state_lock !== null) {
258 258 var keys = Object.keys(this.state_lock);
259 259 for (var i=0; i<keys.length; i++) {
260 260 var key = keys[i];
261 261 if (attrs[key] === this.state_lock[key]) {
262 262 delete attrs[key];
263 263 }
264 264 }
265 265 }
266 266
267 267 // Only sync if there are attributes to send to the back-end.
268 268 attrs = this._pack_models(attrs);
269 269 if (_.size(attrs) > 0) {
270 270
271 271 // If this message was sent via backbone itself, it will not
272 272 // have any callbacks. It's important that we create callbacks
273 273 // so we can listen for status messages, etc...
274 274 var callbacks = options.callbacks || this.callbacks();
275 275
276 276 // Check throttle.
277 277 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
278 278 // The throttle has been exceeded, buffer the current msg so
279 279 // it can be sent once the kernel has finished processing
280 280 // some of the existing messages.
281 281
282 282 // Combine updates if it is a 'patch' sync, otherwise replace updates
283 283 switch (method) {
284 284 case 'patch':
285 285 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
286 286 break;
287 287 case 'update':
288 288 case 'create':
289 289 this.msg_buffer = attrs;
290 290 break;
291 291 default:
292 292 error();
293 293 return false;
294 294 }
295 295 this.msg_buffer_callbacks = callbacks;
296 296
297 297 } else {
298 298 // We haven't exceeded the throttle, send the message like
299 299 // normal.
300 300 var data = {method: 'backbone', sync_data: attrs};
301 301 this.comm.send(data, callbacks);
302 302 this.pending_msgs++;
303 303 }
304 304 }
305 305 // Since the comm is a one-way communication, assume the message
306 306 // arrived. Don't call success since we don't have a model back from the server
307 307 // this means we miss out on the 'sync' event.
308 308 this._buffered_state_diff = {};
309 309 },
310 310
311 311 save_changes: function(callbacks) {
312 312 /**
313 313 * Push this model's state to the back-end
314 314 *
315 315 * This invokes a Backbone.Sync.
316 316 */
317 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
317 if (this.comm_live) {
318 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
319 }
318 320 },
319 321
320 322 _pack_models: function(value) {
321 323 /**
322 324 * Replace models with model ids recursively.
323 325 */
324 326 var that = this;
325 327 var packed;
326 328 if (value instanceof Backbone.Model) {
327 329 return "IPY_MODEL_" + value.id;
328 330
329 331 } else if ($.isArray(value)) {
330 332 packed = [];
331 333 _.each(value, function(sub_value, key) {
332 334 packed.push(that._pack_models(sub_value));
333 335 });
334 336 return packed;
335 337 } else if (value instanceof Date || value instanceof String) {
336 338 return value;
337 339 } else if (value instanceof Object) {
338 340 packed = {};
339 341 _.each(value, function(sub_value, key) {
340 342 packed[key] = that._pack_models(sub_value);
341 343 });
342 344 return packed;
343 345
344 346 } else {
345 347 return value;
346 348 }
347 349 },
348 350
349 351 _unpack_models: function(value) {
350 352 /**
351 353 * Replace model ids with models recursively.
352 354 */
353 355 var that = this;
354 356 var unpacked;
355 357 if ($.isArray(value)) {
356 358 unpacked = [];
357 359 _.each(value, function(sub_value, key) {
358 360 unpacked.push(that._unpack_models(sub_value));
359 361 });
360 362 return Promise.all(unpacked);
361 363 } else if (value instanceof Object) {
362 364 unpacked = {};
363 365 _.each(value, function(sub_value, key) {
364 366 unpacked[key] = that._unpack_models(sub_value);
365 367 });
366 368 return utils.resolve_promises_dict(unpacked);
367 369 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
368 370 // get_model returns a promise already
369 371 return this.widget_manager.get_model(value.slice(10, value.length));
370 372 } else {
371 373 return Promise.resolve(value);
372 374 }
373 375 },
374 376
375 377 on_some_change: function(keys, callback, context) {
376 378 /**
377 379 * on_some_change(["key1", "key2"], foo, context) differs from
378 380 * on("change:key1 change:key2", foo, context).
379 381 * If the widget attributes key1 and key2 are both modified,
380 382 * the second form will result in foo being called twice
381 383 * while the first will call foo only once.
382 384 */
383 385 this.on('change', function() {
384 386 if (keys.some(this.hasChanged, this)) {
385 387 callback.apply(context);
386 388 }
387 389 }, this);
388 390
389 391 },
390 392 });
391 393 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
392 394
393 395
394 396 var WidgetView = Backbone.View.extend({
395 397 initialize: function(parameters) {
396 398 /**
397 399 * Public constructor.
398 400 */
399 401 this.model.on('change',this.update,this);
400 402
401 403 // Bubble the comm live events.
402 404 this.model.on('comm:live', function() {
403 405 this.trigger('comm:live', this);
404 406 }, this);
405 407 this.model.on('comm:dead', function() {
406 408 this.trigger('comm:dead', this);
407 409 }, this);
408 410
409 411 this.options = parameters.options;
410 412 this.on('displayed', function() {
411 413 this.is_displayed = true;
412 414 }, this);
413 415 },
414 416
415 417 update: function(){
416 418 /**
417 419 * Triggered on model change.
418 420 *
419 421 * Update view to be consistent with this.model
420 422 */
421 423 },
422 424
423 425 create_child_view: function(child_model, options) {
424 426 /**
425 427 * Create and promise that resolves to a child view of a given model
426 428 */
427 429 var that = this;
428 430 options = $.extend({ parent: this }, options || {});
429 431 return this.model.widget_manager.create_view(child_model, options).catch(utils.reject("Couldn't create child view"), true);
430 432 },
431 433
432 434 callbacks: function(){
433 435 /**
434 436 * Create msg callbacks for a comm msg.
435 437 */
436 438 return this.model.callbacks(this);
437 439 },
438 440
439 441 render: function(){
440 442 /**
441 443 * Render the view.
442 444 *
443 445 * By default, this is only called the first time the view is created
444 446 */
445 447 },
446 448
447 449 send: function (content) {
448 450 /**
449 451 * Send a custom msg associated with this view.
450 452 */
451 453 this.model.send(content, this.callbacks());
452 454 },
453 455
454 456 touch: function () {
455 457 this.model.save_changes(this.callbacks());
456 458 },
457 459
458 460 after_displayed: function (callback, context) {
459 461 /**
460 462 * Calls the callback right away is the view is already displayed
461 463 * otherwise, register the callback to the 'displayed' event.
462 464 */
463 465 if (this.is_displayed) {
464 466 callback.apply(context);
465 467 } else {
466 468 this.on('displayed', callback, context);
467 469 }
468 470 },
469 471
470 472 remove: function () {
471 473 // Raise a remove event when the view is removed.
472 474 WidgetView.__super__.remove.apply(this, arguments);
473 475 this.trigger('remove');
474 476 }
475 477 });
476 478
477 479
478 480 var DOMWidgetView = WidgetView.extend({
479 481 initialize: function (parameters) {
480 482 /**
481 483 * Public constructor
482 484 */
483 485 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
484 486 this.model.on('change:visible', this.update_visible, this);
485 487 this.model.on('change:_css', this.update_css, this);
486 488
487 489 this.model.on('change:_dom_classes', function(model, new_classes) {
488 490 var old_classes = model.previous('_dom_classes');
489 491 this.update_classes(old_classes, new_classes);
490 492 }, this);
491 493
492 494 this.model.on('change:color', function (model, value) {
493 495 this.update_attr('color', value); }, this);
494 496
495 497 this.model.on('change:background_color', function (model, value) {
496 498 this.update_attr('background', value); }, this);
497 499
498 500 this.model.on('change:width', function (model, value) {
499 501 this.update_attr('width', value); }, this);
500 502
501 503 this.model.on('change:height', function (model, value) {
502 504 this.update_attr('height', value); }, this);
503 505
504 506 this.model.on('change:border_color', function (model, value) {
505 507 this.update_attr('border-color', value); }, this);
506 508
507 509 this.model.on('change:border_width', function (model, value) {
508 510 this.update_attr('border-width', value); }, this);
509 511
510 512 this.model.on('change:border_style', function (model, value) {
511 513 this.update_attr('border-style', value); }, this);
512 514
513 515 this.model.on('change:font_style', function (model, value) {
514 516 this.update_attr('font-style', value); }, this);
515 517
516 518 this.model.on('change:font_weight', function (model, value) {
517 519 this.update_attr('font-weight', value); }, this);
518 520
519 521 this.model.on('change:font_size', function (model, value) {
520 522 this.update_attr('font-size', this._default_px(value)); }, this);
521 523
522 524 this.model.on('change:font_family', function (model, value) {
523 525 this.update_attr('font-family', value); }, this);
524 526
525 527 this.model.on('change:padding', function (model, value) {
526 528 this.update_attr('padding', value); }, this);
527 529
528 530 this.model.on('change:margin', function (model, value) {
529 531 this.update_attr('margin', this._default_px(value)); }, this);
530 532
531 533 this.model.on('change:border_radius', function (model, value) {
532 534 this.update_attr('border-radius', this._default_px(value)); }, this);
533 535
534 536 this.after_displayed(function() {
535 537 this.update_visible(this.model, this.model.get("visible"));
536 538 this.update_classes([], this.model.get('_dom_classes'));
537 539
538 540 this.update_attr('color', this.model.get('color'));
539 541 this.update_attr('background', this.model.get('background_color'));
540 542 this.update_attr('width', this.model.get('width'));
541 543 this.update_attr('height', this.model.get('height'));
542 544 this.update_attr('border-color', this.model.get('border_color'));
543 545 this.update_attr('border-width', this.model.get('border_width'));
544 546 this.update_attr('border-style', this.model.get('border_style'));
545 547 this.update_attr('font-style', this.model.get('font_style'));
546 548 this.update_attr('font-weight', this.model.get('font_weight'));
547 549 this.update_attr('font-size', this._default_px(this.model.get('font_size')));
548 550 this.update_attr('font-family', this.model.get('font_family'));
549 551 this.update_attr('padding', this.model.get('padding'));
550 552 this.update_attr('margin', this._default_px(this.model.get('margin')));
551 553 this.update_attr('border-radius', this._default_px(this.model.get('border_radius')));
552 554
553 555 this.update_css(this.model, this.model.get("_css"));
554 556 }, this);
555 557 },
556 558
557 559 _default_px: function(value) {
558 560 /**
559 561 * Makes browser interpret a numerical string as a pixel value.
560 562 */
561 563 if (/^\d+\.?(\d+)?$/.test(value.trim())) {
562 564 return value.trim() + 'px';
563 565 }
564 566 return value;
565 567 },
566 568
567 569 update_attr: function(name, value) {
568 570 /**
569 571 * Set a css attr of the widget view.
570 572 */
571 573 this.$el.css(name, value);
572 574 },
573 575
574 576 update_visible: function(model, value) {
575 577 /**
576 578 * Update visibility
577 579 */
578 580 switch(value) {
579 581 case null: // python None
580 582 this.$el.show().css('visibility', 'hidden'); break;
581 583 case false:
582 584 this.$el.hide(); break;
583 585 case true:
584 586 this.$el.show().css('visibility', ''); break;
585 587 }
586 588 },
587 589
588 590 update_css: function (model, css) {
589 591 /**
590 592 * Update the css styling of this view.
591 593 */
592 594 if (css === undefined) {return;}
593 595 for (var i = 0; i < css.length; i++) {
594 596 // Apply the css traits to all elements that match the selector.
595 597 var selector = css[i][0];
596 598 var elements = this._get_selector_element(selector);
597 599 if (elements.length > 0) {
598 600 var trait_key = css[i][1];
599 601 var trait_value = css[i][2];
600 602 elements.css(trait_key ,trait_value);
601 603 }
602 604 }
603 605 },
604 606
605 607 update_classes: function (old_classes, new_classes, $el) {
606 608 /**
607 609 * Update the DOM classes applied to an element, default to this.$el.
608 610 */
609 611 if ($el===undefined) {
610 612 $el = this.$el;
611 613 }
612 614 _.difference(old_classes, new_classes).map(function(c) {$el.removeClass(c);})
613 615 _.difference(new_classes, old_classes).map(function(c) {$el.addClass(c);})
614 616 },
615 617
616 618 update_mapped_classes: function(class_map, trait_name, previous_trait_value, $el) {
617 619 /**
618 620 * Update the DOM classes applied to the widget based on a single
619 621 * trait's value.
620 622 *
621 623 * Given a trait value classes map, this function automatically
622 624 * handles applying the appropriate classes to the widget element
623 625 * and removing classes that are no longer valid.
624 626 *
625 627 * Parameters
626 628 * ----------
627 629 * class_map: dictionary
628 630 * Dictionary of trait values to class lists.
629 631 * Example:
630 632 * {
631 633 * success: ['alert', 'alert-success'],
632 634 * info: ['alert', 'alert-info'],
633 635 * warning: ['alert', 'alert-warning'],
634 636 * danger: ['alert', 'alert-danger']
635 637 * };
636 638 * trait_name: string
637 639 * Name of the trait to check the value of.
638 640 * previous_trait_value: optional string, default ''
639 641 * Last trait value
640 642 * $el: optional jQuery element handle, defaults to this.$el
641 643 * Element that the classes are applied to.
642 644 */
643 645 var key = previous_trait_value;
644 646 if (key === undefined) {
645 647 key = this.model.previous(trait_name);
646 648 }
647 649 var old_classes = class_map[key] ? class_map[key] : [];
648 650 key = this.model.get(trait_name);
649 651 var new_classes = class_map[key] ? class_map[key] : [];
650 652
651 653 this.update_classes(old_classes, new_classes, $el || this.$el);
652 654 },
653 655
654 656 _get_selector_element: function (selector) {
655 657 /**
656 658 * Get the elements via the css selector.
657 659 */
658 660 var elements;
659 661 if (!selector) {
660 662 elements = this.$el;
661 663 } else {
662 664 elements = this.$el.find(selector).addBack(selector);
663 665 }
664 666 return elements;
665 667 },
666 668
667 669 typeset: function(element, text){
668 670 utils.typeset.apply(null, arguments);
669 671 },
670 672 });
671 673
672 674
673 675 var ViewList = function(create_view, remove_view, context) {
674 676 /**
675 677 * - create_view and remove_view are default functions called when adding or removing views
676 678 * - create_view takes a model and returns a view or a promise for a view for that model
677 679 * - remove_view takes a view and destroys it (including calling `view.remove()`)
678 680 * - each time the update() function is called with a new list, the create and remove
679 681 * callbacks will be called in an order so that if you append the views created in the
680 682 * create callback and remove the views in the remove callback, you will duplicate
681 683 * the order of the list.
682 684 * - the remove callback defaults to just removing the view (e.g., pass in null for the second parameter)
683 685 * - the context defaults to the created ViewList. If you pass another context, the create and remove
684 686 * will be called in that context.
685 687 */
686 688
687 689 this.initialize.apply(this, arguments);
688 690 };
689 691
690 692 _.extend(ViewList.prototype, {
691 693 initialize: function(create_view, remove_view, context) {
692 694 this._handler_context = context || this;
693 695 this._models = [];
694 696 this.views = []; // list of promises for views
695 697 this._create_view = create_view;
696 698 this._remove_view = remove_view || function(view) {view.remove();};
697 699 },
698 700
699 701 update: function(new_models, create_view, remove_view, context) {
700 702 /**
701 703 * the create_view, remove_view, and context arguments override the defaults
702 704 * specified when the list is created.
703 705 * after this function, the .views attribute is a list of promises for views
704 706 * if you want to perform some action on the list of views, do something like
705 707 * `Promise.all(myviewlist.views).then(function(views) {...});`
706 708 */
707 709 var remove = remove_view || this._remove_view;
708 710 var create = create_view || this._create_view;
709 711 context = context || this._handler_context;
710 712 var i = 0;
711 713 // first, skip past the beginning of the lists if they are identical
712 714 for (; i < new_models.length; i++) {
713 715 if (i >= this._models.length || new_models[i] !== this._models[i]) {
714 716 break;
715 717 }
716 718 }
717 719
718 720 var first_removed = i;
719 721 // Remove the non-matching items from the old list.
720 722 var removed = this.views.splice(first_removed, this.views.length-first_removed);
721 723 for (var j = 0; j < removed.length; j++) {
722 724 removed[j].then(function(view) {
723 725 remove.call(context, view)
724 726 });
725 727 }
726 728
727 729 // Add the rest of the new list items.
728 730 for (; i < new_models.length; i++) {
729 731 this.views.push(Promise.resolve(create.call(context, new_models[i])));
730 732 }
731 733 // make a copy of the input array
732 734 this._models = new_models.slice();
733 735 },
734 736
735 737 remove: function() {
736 738 /**
737 739 * removes every view in the list; convenience function for `.update([])`
738 740 * that should be faster
739 741 * returns a promise that resolves after this removal is done
740 742 */
741 743 var that = this;
742 744 return Promise.all(this.views).then(function(views) {
743 745 for (var i = 0; i < that.views.length; i++) {
744 746 that._remove_view.call(that._handler_context, views[i]);
745 747 }
746 748 that.views = [];
747 749 that._models = [];
748 750 });
749 751 },
750 752 });
751 753
752 754 var widget = {
753 755 'WidgetModel': WidgetModel,
754 756 'WidgetView': WidgetView,
755 757 'DOMWidgetView': DOMWidgetView,
756 758 'ViewList': ViewList,
757 759 };
758 760
759 761 // For backwards compatability.
760 762 $.extend(IPython, widget);
761 763
762 764 return widget;
763 765 });
General Comments 0
You need to be logged in to leave comments. Login now