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