##// END OF EJS Templates
state_lock loop
Sylvain Corlay -
Show More
@@ -1,501 +1,502
1 // Copyright (c) IPython Development Team.
1 // Copyright (c) IPython Development Team.
2 // Distributed under the terms of the Modified BSD License.
2 // Distributed under the terms of the Modified BSD License.
3
3
4 define(["widgets/js/manager",
4 define(["widgets/js/manager",
5 "underscore",
5 "underscore",
6 "backbone",
6 "backbone",
7 "jquery",
7 "jquery",
8 "base/js/namespace",
8 "base/js/namespace",
9 ], function(widgetmanager, _, Backbone, $, IPython){
9 ], function(widgetmanager, _, Backbone, $, IPython){
10
10
11 var WidgetModel = Backbone.Model.extend({
11 var WidgetModel = Backbone.Model.extend({
12 constructor: function (widget_manager, model_id, comm) {
12 constructor: function (widget_manager, model_id, comm) {
13 // Constructor
13 // Constructor
14 //
14 //
15 // Creates a WidgetModel instance.
15 // Creates a WidgetModel instance.
16 //
16 //
17 // Parameters
17 // Parameters
18 // ----------
18 // ----------
19 // widget_manager : WidgetManager instance
19 // widget_manager : WidgetManager instance
20 // model_id : string
20 // model_id : string
21 // An ID unique to this model.
21 // An ID unique to this model.
22 // comm : Comm instance (optional)
22 // comm : Comm instance (optional)
23 this.widget_manager = widget_manager;
23 this.widget_manager = widget_manager;
24 this._buffered_state_diff = {};
24 this._buffered_state_diff = {};
25 this.pending_msgs = 0;
25 this.pending_msgs = 0;
26 this.msg_buffer = null;
26 this.msg_buffer = null;
27 this.state_lock = null;
27 this.state_lock = null;
28 this.id = model_id;
28 this.id = model_id;
29 this.views = [];
29 this.views = [];
30
30
31 if (comm !== undefined) {
31 if (comm !== undefined) {
32 // Remember comm associated with the model.
32 // Remember comm associated with the model.
33 this.comm = comm;
33 this.comm = comm;
34 comm.model = this;
34 comm.model = this;
35
35
36 // Hook comm messages up to model.
36 // Hook comm messages up to model.
37 comm.on_close($.proxy(this._handle_comm_closed, this));
37 comm.on_close($.proxy(this._handle_comm_closed, this));
38 comm.on_msg($.proxy(this._handle_comm_msg, this));
38 comm.on_msg($.proxy(this._handle_comm_msg, this));
39 }
39 }
40 return Backbone.Model.apply(this);
40 return Backbone.Model.apply(this);
41 },
41 },
42
42
43 send: function (content, callbacks) {
43 send: function (content, callbacks) {
44 // Send a custom msg over the comm.
44 // Send a custom msg over the comm.
45 if (this.comm !== undefined) {
45 if (this.comm !== undefined) {
46 var data = {method: 'custom', content: content};
46 var data = {method: 'custom', content: content};
47 this.comm.send(data, callbacks);
47 this.comm.send(data, callbacks);
48 this.pending_msgs++;
48 this.pending_msgs++;
49 }
49 }
50 },
50 },
51
51
52 _handle_comm_closed: function (msg) {
52 _handle_comm_closed: function (msg) {
53 // Handle when a widget is closed.
53 // Handle when a widget is closed.
54 this.trigger('comm:close');
54 this.trigger('comm:close');
55 delete this.comm.model; // Delete ref so GC will collect widget model.
55 delete this.comm.model; // Delete ref so GC will collect widget model.
56 delete this.comm;
56 delete this.comm;
57 delete this.model_id; // Delete id from model so widget manager cleans up.
57 delete this.model_id; // Delete id from model so widget manager cleans up.
58 _.each(this.views, function(view, i) {
58 _.each(this.views, function(view, i) {
59 view.remove();
59 view.remove();
60 });
60 });
61 },
61 },
62
62
63 _handle_comm_msg: function (msg) {
63 _handle_comm_msg: function (msg) {
64 // Handle incoming comm msg.
64 // Handle incoming comm msg.
65 var method = msg.content.data.method;
65 var method = msg.content.data.method;
66 switch (method) {
66 switch (method) {
67 case 'update':
67 case 'update':
68 this.apply_update(msg.content.data.state);
68 this.apply_update(msg.content.data.state);
69 break;
69 break;
70 case 'custom':
70 case 'custom':
71 this.trigger('msg:custom', msg.content.data.content);
71 this.trigger('msg:custom', msg.content.data.content);
72 break;
72 break;
73 case 'display':
73 case 'display':
74 this.widget_manager.display_view(msg, this);
74 this.widget_manager.display_view(msg, this);
75 break;
75 break;
76 }
76 }
77 },
77 },
78
78
79 apply_update: function (state) {
79 apply_update: function (state) {
80 // Handle when a widget is updated via the python side.
80 // Handle when a widget is updated via the python side.
81 this.state_lock = state;
81 this.state_lock = state;
82 try {
82 try {
83 var that = this;
83 var that = this;
84 WidgetModel.__super__.set.apply(this, [Object.keys(state).reduce(function(obj, key) {
84 WidgetModel.__super__.set.apply(this, [Object.keys(state).reduce(function(obj, key) {
85 obj[key] = that._unpack_models(state[key]);
85 obj[key] = that._unpack_models(state[key]);
86 return obj;
86 return obj;
87 }, {})]);
87 }, {})]);
88 } finally {
88 } finally {
89 this.state_lock = null;
89 this.state_lock = null;
90 }
90 }
91 },
91 },
92
92
93 _handle_status: function (msg, callbacks) {
93 _handle_status: function (msg, callbacks) {
94 // Handle status msgs.
94 // Handle status msgs.
95
95
96 // execution_state : ('busy', 'idle', 'starting')
96 // execution_state : ('busy', 'idle', 'starting')
97 if (this.comm !== undefined) {
97 if (this.comm !== undefined) {
98 if (msg.content.execution_state ==='idle') {
98 if (msg.content.execution_state ==='idle') {
99 // Send buffer if this message caused another message to be
99 // Send buffer if this message caused another message to be
100 // throttled.
100 // throttled.
101 if (this.msg_buffer !== null &&
101 if (this.msg_buffer !== null &&
102 (this.get('msg_throttle') || 3) === this.pending_msgs) {
102 (this.get('msg_throttle') || 3) === this.pending_msgs) {
103 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
103 var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
104 this.comm.send(data, callbacks);
104 this.comm.send(data, callbacks);
105 this.msg_buffer = null;
105 this.msg_buffer = null;
106 } else {
106 } else {
107 --this.pending_msgs;
107 --this.pending_msgs;
108 }
108 }
109 }
109 }
110 }
110 }
111 },
111 },
112
112
113 callbacks: function(view) {
113 callbacks: function(view) {
114 // Create msg callbacks for a comm msg.
114 // Create msg callbacks for a comm msg.
115 var callbacks = this.widget_manager.callbacks(view);
115 var callbacks = this.widget_manager.callbacks(view);
116
116
117 if (callbacks.iopub === undefined) {
117 if (callbacks.iopub === undefined) {
118 callbacks.iopub = {};
118 callbacks.iopub = {};
119 }
119 }
120
120
121 var that = this;
121 var that = this;
122 callbacks.iopub.status = function (msg) {
122 callbacks.iopub.status = function (msg) {
123 that._handle_status(msg, callbacks);
123 that._handle_status(msg, callbacks);
124 };
124 };
125 return callbacks;
125 return callbacks;
126 },
126 },
127
127
128 set: function(key, val, options) {
128 set: function(key, val, options) {
129 // Set a value.
129 // Set a value.
130 var return_value = WidgetModel.__super__.set.apply(this, arguments);
130 var return_value = WidgetModel.__super__.set.apply(this, arguments);
131
131
132 // Backbone only remembers the diff of the most recent set()
132 // Backbone only remembers the diff of the most recent set()
133 // operation. Calling set multiple times in a row results in a
133 // operation. Calling set multiple times in a row results in a
134 // loss of diff information. Here we keep our own running diff.
134 // loss of diff information. Here we keep our own running diff.
135 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
135 this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
136 return return_value;
136 return return_value;
137 },
137 },
138
138
139 sync: function (method, model, options) {
139 sync: function (method, model, options) {
140 // Handle sync to the back-end. Called when a model.save() is called.
140 // Handle sync to the back-end. Called when a model.save() is called.
141
141
142 // Make sure a comm exists.
142 // Make sure a comm exists.
143 var error = options.error || function() {
143 var error = options.error || function() {
144 console.error('Backbone sync error:', arguments);
144 console.error('Backbone sync error:', arguments);
145 };
145 };
146 if (this.comm === undefined) {
146 if (this.comm === undefined) {
147 error();
147 error();
148 return false;
148 return false;
149 }
149 }
150
150
151 // Delete any key value pairs that the back-end already knows about.
151 // Delete any key value pairs that the back-end already knows about.
152 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
152 var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
153 if (this.state_lock !== null) {
153 if (this.state_lock !== null) {
154 var keys = Object.keys(this.state_lock);
154 var keys = Object.keys(this.state_lock);
155 for (var i=0; i<keys.length; i++)
155 for (var i=0; i<keys.length; i++) {
156 var key = keys[i];
156 var key = keys[i];
157 if (attrs[key] === this.state_lock[key]) {
157 if (attrs[key] === this.state_lock[key]) {
158 delete attrs[key];
158 delete attrs[key];
159 }
159 }
160 }
160 }
161 }
161
162
162 // Only sync if there are attributes to send to the back-end.
163 // Only sync if there are attributes to send to the back-end.
163 attrs = this._pack_models(attrs);
164 attrs = this._pack_models(attrs);
164 if (_.size(attrs) > 0) {
165 if (_.size(attrs) > 0) {
165
166
166 // If this message was sent via backbone itself, it will not
167 // If this message was sent via backbone itself, it will not
167 // have any callbacks. It's important that we create callbacks
168 // have any callbacks. It's important that we create callbacks
168 // so we can listen for status messages, etc...
169 // so we can listen for status messages, etc...
169 var callbacks = options.callbacks || this.callbacks();
170 var callbacks = options.callbacks || this.callbacks();
170
171
171 // Check throttle.
172 // Check throttle.
172 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
173 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
173 // The throttle has been exceeded, buffer the current msg so
174 // The throttle has been exceeded, buffer the current msg so
174 // it can be sent once the kernel has finished processing
175 // it can be sent once the kernel has finished processing
175 // some of the existing messages.
176 // some of the existing messages.
176
177
177 // Combine updates if it is a 'patch' sync, otherwise replace updates
178 // Combine updates if it is a 'patch' sync, otherwise replace updates
178 switch (method) {
179 switch (method) {
179 case 'patch':
180 case 'patch':
180 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
181 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
181 break;
182 break;
182 case 'update':
183 case 'update':
183 case 'create':
184 case 'create':
184 this.msg_buffer = attrs;
185 this.msg_buffer = attrs;
185 break;
186 break;
186 default:
187 default:
187 error();
188 error();
188 return false;
189 return false;
189 }
190 }
190 this.msg_buffer_callbacks = callbacks;
191 this.msg_buffer_callbacks = callbacks;
191
192
192 } else {
193 } else {
193 // We haven't exceeded the throttle, send the message like
194 // We haven't exceeded the throttle, send the message like
194 // normal.
195 // normal.
195 var data = {method: 'backbone', sync_data: attrs};
196 var data = {method: 'backbone', sync_data: attrs};
196 this.comm.send(data, callbacks);
197 this.comm.send(data, callbacks);
197 this.pending_msgs++;
198 this.pending_msgs++;
198 }
199 }
199 }
200 }
200 // Since the comm is a one-way communication, assume the message
201 // Since the comm is a one-way communication, assume the message
201 // arrived. Don't call success since we don't have a model back from the server
202 // arrived. Don't call success since we don't have a model back from the server
202 // this means we miss out on the 'sync' event.
203 // this means we miss out on the 'sync' event.
203 this._buffered_state_diff = {};
204 this._buffered_state_diff = {};
204 },
205 },
205
206
206 save_changes: function(callbacks) {
207 save_changes: function(callbacks) {
207 // Push this model's state to the back-end
208 // Push this model's state to the back-end
208 //
209 //
209 // This invokes a Backbone.Sync.
210 // This invokes a Backbone.Sync.
210 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
211 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
211 },
212 },
212
213
213 _pack_models: function(value) {
214 _pack_models: function(value) {
214 // Replace models with model ids recursively.
215 // Replace models with model ids recursively.
215 var that = this;
216 var that = this;
216 var packed;
217 var packed;
217 if (value instanceof Backbone.Model) {
218 if (value instanceof Backbone.Model) {
218 return "IPY_MODEL_" + value.id;
219 return "IPY_MODEL_" + value.id;
219
220
220 } else if ($.isArray(value)) {
221 } else if ($.isArray(value)) {
221 packed = [];
222 packed = [];
222 _.each(value, function(sub_value, key) {
223 _.each(value, function(sub_value, key) {
223 packed.push(that._pack_models(sub_value));
224 packed.push(that._pack_models(sub_value));
224 });
225 });
225 return packed;
226 return packed;
226
227
227 } else if (value instanceof Object) {
228 } else if (value instanceof Object) {
228 packed = {};
229 packed = {};
229 _.each(value, function(sub_value, key) {
230 _.each(value, function(sub_value, key) {
230 packed[key] = that._pack_models(sub_value);
231 packed[key] = that._pack_models(sub_value);
231 });
232 });
232 return packed;
233 return packed;
233
234
234 } else {
235 } else {
235 return value;
236 return value;
236 }
237 }
237 },
238 },
238
239
239 _unpack_models: function(value) {
240 _unpack_models: function(value) {
240 // Replace model ids with models recursively.
241 // Replace model ids with models recursively.
241 var that = this;
242 var that = this;
242 var unpacked;
243 var unpacked;
243 if ($.isArray(value)) {
244 if ($.isArray(value)) {
244 unpacked = [];
245 unpacked = [];
245 _.each(value, function(sub_value, key) {
246 _.each(value, function(sub_value, key) {
246 unpacked.push(that._unpack_models(sub_value));
247 unpacked.push(that._unpack_models(sub_value));
247 });
248 });
248 return unpacked;
249 return unpacked;
249
250
250 } else if (value instanceof Object) {
251 } else if (value instanceof Object) {
251 unpacked = {};
252 unpacked = {};
252 _.each(value, function(sub_value, key) {
253 _.each(value, function(sub_value, key) {
253 unpacked[key] = that._unpack_models(sub_value);
254 unpacked[key] = that._unpack_models(sub_value);
254 });
255 });
255 return unpacked;
256 return unpacked;
256
257
257 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
258 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
258 var model = this.widget_manager.get_model(value.slice(10, value.length));
259 var model = this.widget_manager.get_model(value.slice(10, value.length));
259 if (model) {
260 if (model) {
260 return model;
261 return model;
261 } else {
262 } else {
262 return value;
263 return value;
263 }
264 }
264 } else {
265 } else {
265 return value;
266 return value;
266 }
267 }
267 },
268 },
268
269
269 on_atomic_change: function(keys, callback, context) {
270 on_atomic_change: function(keys, callback, context) {
270 // on__atomic_change(["key1", "key2"], foo, context) differs from
271 // on__atomic_change(["key1", "key2"], foo, context) differs from
271 // on("change:key1 change:key2", foo, context).
272 // on("change:key1 change:key2", foo, context).
272 // If the widget attributes key1 and key2 are both modified,
273 // If the widget attributes key1 and key2 are both modified,
273 // the second form will result in foo being called twice
274 // the second form will result in foo being called twice
274 // while the first will call foo only once.
275 // while the first will call foo only once.
275 this.on('change', function() {
276 this.on('change', function() {
276 if (keys.some(this.hasChanged, this)) {
277 if (keys.some(this.hasChanged, this)) {
277 callback.apply(context);
278 callback.apply(context);
278 }
279 }
279 }, this);
280 }, this);
280
281
281 },
282 },
282 });
283 });
283 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
284 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
284
285
285
286
286 var WidgetView = Backbone.View.extend({
287 var WidgetView = Backbone.View.extend({
287 initialize: function(parameters) {
288 initialize: function(parameters) {
288 // Public constructor.
289 // Public constructor.
289 this.model.on('change',this.update,this);
290 this.model.on('change',this.update,this);
290 this.options = parameters.options;
291 this.options = parameters.options;
291 this.child_model_views = {};
292 this.child_model_views = {};
292 this.child_views = {};
293 this.child_views = {};
293 this.model.views.push(this);
294 this.model.views.push(this);
294 this.id = this.id || IPython.utils.uuid();
295 this.id = this.id || IPython.utils.uuid();
295 this.on('displayed', function() {
296 this.on('displayed', function() {
296 this.is_displayed = true;
297 this.is_displayed = true;
297 }, this);
298 }, this);
298 },
299 },
299
300
300 update: function(){
301 update: function(){
301 // Triggered on model change.
302 // Triggered on model change.
302 //
303 //
303 // Update view to be consistent with this.model
304 // Update view to be consistent with this.model
304 },
305 },
305
306
306 create_child_view: function(child_model, options) {
307 create_child_view: function(child_model, options) {
307 // Create and return a child view.
308 // Create and return a child view.
308 //
309 //
309 // -given a model and (optionally) a view name if the view name is
310 // -given a model and (optionally) a view name if the view name is
310 // not given, it defaults to the model's default view attribute.
311 // not given, it defaults to the model's default view attribute.
311
312
312 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
313 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
313 // it would be great to have the widget manager add the cell metadata
314 // it would be great to have the widget manager add the cell metadata
314 // to the subview without having to add it here.
315 // to the subview without having to add it here.
315 options = $.extend({ parent: this }, options || {});
316 options = $.extend({ parent: this }, options || {});
316 var child_view = this.model.widget_manager.create_view(child_model, options, this);
317 var child_view = this.model.widget_manager.create_view(child_model, options, this);
317
318
318 // Associate the view id with the model id.
319 // Associate the view id with the model id.
319 if (this.child_model_views[child_model.id] === undefined) {
320 if (this.child_model_views[child_model.id] === undefined) {
320 this.child_model_views[child_model.id] = [];
321 this.child_model_views[child_model.id] = [];
321 }
322 }
322 this.child_model_views[child_model.id].push(child_view.id);
323 this.child_model_views[child_model.id].push(child_view.id);
323
324
324 // Remember the view by id.
325 // Remember the view by id.
325 this.child_views[child_view.id] = child_view;
326 this.child_views[child_view.id] = child_view;
326 return child_view;
327 return child_view;
327 },
328 },
328
329
329 pop_child_view: function(child_model) {
330 pop_child_view: function(child_model) {
330 // Delete a child view that was previously created using create_child_view.
331 // Delete a child view that was previously created using create_child_view.
331 var view_ids = this.child_model_views[child_model.id];
332 var view_ids = this.child_model_views[child_model.id];
332 if (view_ids !== undefined) {
333 if (view_ids !== undefined) {
333
334
334 // Only delete the first view in the list.
335 // Only delete the first view in the list.
335 var view_id = view_ids[0];
336 var view_id = view_ids[0];
336 var view = this.child_views[view_id];
337 var view = this.child_views[view_id];
337 delete this.child_views[view_id];
338 delete this.child_views[view_id];
338 view_ids.splice(0,1);
339 view_ids.splice(0,1);
339 child_model.views.pop(view);
340 child_model.views.pop(view);
340
341
341 // Remove the view list specific to this model if it is empty.
342 // Remove the view list specific to this model if it is empty.
342 if (view_ids.length === 0) {
343 if (view_ids.length === 0) {
343 delete this.child_model_views[child_model.id];
344 delete this.child_model_views[child_model.id];
344 }
345 }
345 return view;
346 return view;
346 }
347 }
347 return null;
348 return null;
348 },
349 },
349
350
350 do_diff: function(old_list, new_list, removed_callback, added_callback) {
351 do_diff: function(old_list, new_list, removed_callback, added_callback) {
351 // Difference a changed list and call remove and add callbacks for
352 // Difference a changed list and call remove and add callbacks for
352 // each removed and added item in the new list.
353 // each removed and added item in the new list.
353 //
354 //
354 // Parameters
355 // Parameters
355 // ----------
356 // ----------
356 // old_list : array
357 // old_list : array
357 // new_list : array
358 // new_list : array
358 // removed_callback : Callback(item)
359 // removed_callback : Callback(item)
359 // Callback that is called for each item removed.
360 // Callback that is called for each item removed.
360 // added_callback : Callback(item)
361 // added_callback : Callback(item)
361 // Callback that is called for each item added.
362 // Callback that is called for each item added.
362
363
363 // Walk the lists until an unequal entry is found.
364 // Walk the lists until an unequal entry is found.
364 var i;
365 var i;
365 for (i = 0; i < new_list.length; i++) {
366 for (i = 0; i < new_list.length; i++) {
366 if (i >= old_list.length || new_list[i] !== old_list[i]) {
367 if (i >= old_list.length || new_list[i] !== old_list[i]) {
367 break;
368 break;
368 }
369 }
369 }
370 }
370
371
371 // Remove the non-matching items from the old list.
372 // Remove the non-matching items from the old list.
372 for (var j = i; j < old_list.length; j++) {
373 for (var j = i; j < old_list.length; j++) {
373 removed_callback(old_list[j]);
374 removed_callback(old_list[j]);
374 }
375 }
375
376
376 // Add the rest of the new list items.
377 // Add the rest of the new list items.
377 for (; i < new_list.length; i++) {
378 for (; i < new_list.length; i++) {
378 added_callback(new_list[i]);
379 added_callback(new_list[i]);
379 }
380 }
380 },
381 },
381
382
382 callbacks: function(){
383 callbacks: function(){
383 // Create msg callbacks for a comm msg.
384 // Create msg callbacks for a comm msg.
384 return this.model.callbacks(this);
385 return this.model.callbacks(this);
385 },
386 },
386
387
387 render: function(){
388 render: function(){
388 // Render the view.
389 // Render the view.
389 //
390 //
390 // By default, this is only called the first time the view is created
391 // By default, this is only called the first time the view is created
391 },
392 },
392
393
393 show: function(){
394 show: function(){
394 // Show the widget-area
395 // Show the widget-area
395 if (this.options && this.options.cell &&
396 if (this.options && this.options.cell &&
396 this.options.cell.widget_area !== undefined) {
397 this.options.cell.widget_area !== undefined) {
397 this.options.cell.widget_area.show();
398 this.options.cell.widget_area.show();
398 }
399 }
399 },
400 },
400
401
401 send: function (content) {
402 send: function (content) {
402 // Send a custom msg associated with this view.
403 // Send a custom msg associated with this view.
403 this.model.send(content, this.callbacks());
404 this.model.send(content, this.callbacks());
404 },
405 },
405
406
406 touch: function () {
407 touch: function () {
407 this.model.save_changes(this.callbacks());
408 this.model.save_changes(this.callbacks());
408 },
409 },
409
410
410 after_displayed: function (callback, context) {
411 after_displayed: function (callback, context) {
411 // Calls the callback right away is the view is already displayed
412 // Calls the callback right away is the view is already displayed
412 // otherwise, register the callback to the 'displayed' event.
413 // otherwise, register the callback to the 'displayed' event.
413 if (this.is_displayed) {
414 if (this.is_displayed) {
414 callback.apply(context);
415 callback.apply(context);
415 } else {
416 } else {
416 this.on('displayed', callback, context);
417 this.on('displayed', callback, context);
417 }
418 }
418 },
419 },
419 });
420 });
420
421
421
422
422 var DOMWidgetView = WidgetView.extend({
423 var DOMWidgetView = WidgetView.extend({
423 initialize: function (parameters) {
424 initialize: function (parameters) {
424 // Public constructor
425 // Public constructor
425 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
426 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
426 this.on('displayed', this.show, this);
427 this.on('displayed', this.show, this);
427 this.after_displayed(function() {
428 this.after_displayed(function() {
428 this.update_visible(this.model, this.model.get("visible"));
429 this.update_visible(this.model, this.model.get("visible"));
429 this.update_css(this.model, this.model.get("_css"));
430 this.update_css(this.model, this.model.get("_css"));
430 }, this);
431 }, this);
431 this.model.on('msg:custom', this.on_msg, this);
432 this.model.on('msg:custom', this.on_msg, this);
432 this.model.on('change:visible', this.update_visible, this);
433 this.model.on('change:visible', this.update_visible, this);
433 this.model.on('change:_css', this.update_css, this);
434 this.model.on('change:_css', this.update_css, this);
434 },
435 },
435
436
436 on_msg: function(msg) {
437 on_msg: function(msg) {
437 // Handle DOM specific msgs.
438 // Handle DOM specific msgs.
438 switch(msg.msg_type) {
439 switch(msg.msg_type) {
439 case 'add_class':
440 case 'add_class':
440 this.add_class(msg.selector, msg.class_list);
441 this.add_class(msg.selector, msg.class_list);
441 break;
442 break;
442 case 'remove_class':
443 case 'remove_class':
443 this.remove_class(msg.selector, msg.class_list);
444 this.remove_class(msg.selector, msg.class_list);
444 break;
445 break;
445 }
446 }
446 },
447 },
447
448
448 add_class: function (selector, class_list) {
449 add_class: function (selector, class_list) {
449 // Add a DOM class to an element.
450 // Add a DOM class to an element.
450 this._get_selector_element(selector).addClass(class_list);
451 this._get_selector_element(selector).addClass(class_list);
451 },
452 },
452
453
453 remove_class: function (selector, class_list) {
454 remove_class: function (selector, class_list) {
454 // Remove a DOM class from an element.
455 // Remove a DOM class from an element.
455 this._get_selector_element(selector).removeClass(class_list);
456 this._get_selector_element(selector).removeClass(class_list);
456 },
457 },
457
458
458 update_visible: function(model, value) {
459 update_visible: function(model, value) {
459 // Update visibility
460 // Update visibility
460 this.$el.toggle(value);
461 this.$el.toggle(value);
461 },
462 },
462
463
463 update_css: function (model, css) {
464 update_css: function (model, css) {
464 // Update the css styling of this view.
465 // Update the css styling of this view.
465 var e = this.$el;
466 var e = this.$el;
466 if (css === undefined) {return;}
467 if (css === undefined) {return;}
467 for (var i = 0; i < css.length; i++) {
468 for (var i = 0; i < css.length; i++) {
468 // Apply the css traits to all elements that match the selector.
469 // Apply the css traits to all elements that match the selector.
469 var selector = css[i][0];
470 var selector = css[i][0];
470 var elements = this._get_selector_element(selector);
471 var elements = this._get_selector_element(selector);
471 if (elements.length > 0) {
472 if (elements.length > 0) {
472 var trait_key = css[i][1];
473 var trait_key = css[i][1];
473 var trait_value = css[i][2];
474 var trait_value = css[i][2];
474 elements.css(trait_key ,trait_value);
475 elements.css(trait_key ,trait_value);
475 }
476 }
476 }
477 }
477 },
478 },
478
479
479 _get_selector_element: function (selector) {
480 _get_selector_element: function (selector) {
480 // Get the elements via the css selector.
481 // Get the elements via the css selector.
481 var elements;
482 var elements;
482 if (!selector) {
483 if (!selector) {
483 elements = this.$el;
484 elements = this.$el;
484 } else {
485 } else {
485 elements = this.$el.find(selector).addBack(selector);
486 elements = this.$el.find(selector).addBack(selector);
486 }
487 }
487 return elements;
488 return elements;
488 },
489 },
489 });
490 });
490
491
491 var widget = {
492 var widget = {
492 'WidgetModel': WidgetModel,
493 'WidgetModel': WidgetModel,
493 'WidgetView': WidgetView,
494 'WidgetView': WidgetView,
494 'DOMWidgetView': DOMWidgetView,
495 'DOMWidgetView': DOMWidgetView,
495 };
496 };
496
497
497 // For backwards compatability.
498 // For backwards compatability.
498 $.extend(IPython, widget);
499 $.extend(IPython, widget);
499
500
500 return widget;
501 return widget;
501 });
502 });
General Comments 0
You need to be logged in to leave comments. Login now