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