##// END OF EJS Templates
rename to on_atomic_change
Sylvain Corlay -
Show More
@@ -1,501 +1,501 b''
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 // Only sync if there are attributes to send to the back-end.
162 // Only sync if there are attributes to send to the back-end.
163 attrs = this._pack_models(attrs);
163 attrs = this._pack_models(attrs);
164 if (_.size(attrs) > 0) {
164 if (_.size(attrs) > 0) {
165
165
166 // If this message was sent via backbone itself, it will not
166 // If this message was sent via backbone itself, it will not
167 // have any callbacks. It's important that we create callbacks
167 // have any callbacks. It's important that we create callbacks
168 // so we can listen for status messages, etc...
168 // so we can listen for status messages, etc...
169 var callbacks = options.callbacks || this.callbacks();
169 var callbacks = options.callbacks || this.callbacks();
170
170
171 // Check throttle.
171 // Check throttle.
172 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
172 if (this.pending_msgs >= (this.get('msg_throttle') || 3)) {
173 // The throttle has been exceeded, buffer the current msg so
173 // The throttle has been exceeded, buffer the current msg so
174 // it can be sent once the kernel has finished processing
174 // it can be sent once the kernel has finished processing
175 // some of the existing messages.
175 // some of the existing messages.
176
176
177 // Combine updates if it is a 'patch' sync, otherwise replace updates
177 // Combine updates if it is a 'patch' sync, otherwise replace updates
178 switch (method) {
178 switch (method) {
179 case 'patch':
179 case 'patch':
180 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
180 this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
181 break;
181 break;
182 case 'update':
182 case 'update':
183 case 'create':
183 case 'create':
184 this.msg_buffer = attrs;
184 this.msg_buffer = attrs;
185 break;
185 break;
186 default:
186 default:
187 error();
187 error();
188 return false;
188 return false;
189 }
189 }
190 this.msg_buffer_callbacks = callbacks;
190 this.msg_buffer_callbacks = callbacks;
191
191
192 } else {
192 } else {
193 // We haven't exceeded the throttle, send the message like
193 // We haven't exceeded the throttle, send the message like
194 // normal.
194 // normal.
195 var data = {method: 'backbone', sync_data: attrs};
195 var data = {method: 'backbone', sync_data: attrs};
196 this.comm.send(data, callbacks);
196 this.comm.send(data, callbacks);
197 this.pending_msgs++;
197 this.pending_msgs++;
198 }
198 }
199 }
199 }
200 // Since the comm is a one-way communication, assume the message
200 // 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
201 // 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.
202 // this means we miss out on the 'sync' event.
203 this._buffered_state_diff = {};
203 this._buffered_state_diff = {};
204 },
204 },
205
205
206 save_changes: function(callbacks) {
206 save_changes: function(callbacks) {
207 // Push this model's state to the back-end
207 // Push this model's state to the back-end
208 //
208 //
209 // This invokes a Backbone.Sync.
209 // This invokes a Backbone.Sync.
210 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
210 this.save(this._buffered_state_diff, {patch: true, callbacks: callbacks});
211 },
211 },
212
212
213 _pack_models: function(value) {
213 _pack_models: function(value) {
214 // Replace models with model ids recursively.
214 // Replace models with model ids recursively.
215 var that = this;
215 var that = this;
216 var packed;
216 var packed;
217 if (value instanceof Backbone.Model) {
217 if (value instanceof Backbone.Model) {
218 return "IPY_MODEL_" + value.id;
218 return "IPY_MODEL_" + value.id;
219
219
220 } else if ($.isArray(value)) {
220 } else if ($.isArray(value)) {
221 packed = [];
221 packed = [];
222 _.each(value, function(sub_value, key) {
222 _.each(value, function(sub_value, key) {
223 packed.push(that._pack_models(sub_value));
223 packed.push(that._pack_models(sub_value));
224 });
224 });
225 return packed;
225 return packed;
226
226
227 } else if (value instanceof Object) {
227 } else if (value instanceof Object) {
228 packed = {};
228 packed = {};
229 _.each(value, function(sub_value, key) {
229 _.each(value, function(sub_value, key) {
230 packed[key] = that._pack_models(sub_value);
230 packed[key] = that._pack_models(sub_value);
231 });
231 });
232 return packed;
232 return packed;
233
233
234 } else {
234 } else {
235 return value;
235 return value;
236 }
236 }
237 },
237 },
238
238
239 _unpack_models: function(value) {
239 _unpack_models: function(value) {
240 // Replace model ids with models recursively.
240 // Replace model ids with models recursively.
241 var that = this;
241 var that = this;
242 var unpacked;
242 var unpacked;
243 if ($.isArray(value)) {
243 if ($.isArray(value)) {
244 unpacked = [];
244 unpacked = [];
245 _.each(value, function(sub_value, key) {
245 _.each(value, function(sub_value, key) {
246 unpacked.push(that._unpack_models(sub_value));
246 unpacked.push(that._unpack_models(sub_value));
247 });
247 });
248 return unpacked;
248 return unpacked;
249
249
250 } else if (value instanceof Object) {
250 } else if (value instanceof Object) {
251 unpacked = {};
251 unpacked = {};
252 _.each(value, function(sub_value, key) {
252 _.each(value, function(sub_value, key) {
253 unpacked[key] = that._unpack_models(sub_value);
253 unpacked[key] = that._unpack_models(sub_value);
254 });
254 });
255 return unpacked;
255 return unpacked;
256
256
257 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
257 } else if (typeof value === 'string' && value.slice(0,10) === "IPY_MODEL_") {
258 var model = this.widget_manager.get_model(value.slice(10, value.length));
258 var model = this.widget_manager.get_model(value.slice(10, value.length));
259 if (model) {
259 if (model) {
260 return model;
260 return model;
261 } else {
261 } else {
262 return value;
262 return value;
263 }
263 }
264 } else {
264 } else {
265 return value;
265 return value;
266 }
266 }
267 },
267 },
268
268
269 on_change: function(keys, callback, context) {
269 on_atomic_change: function(keys, callback, context) {
270 // on_change(["key1", "key2"], foo, context) differs from
270 // on__atomic_change(["key1", "key2"], foo, context) differs from
271 // on("change:key1 change:key2", foo, context).
271 // on("change:key1 change:key2", foo, context).
272 // If the widget attributes key1 and key2 are both modified,
272 // If the widget attributes key1 and key2 are both modified,
273 // the second form will result in foo being called twice
273 // the second form will result in foo being called twice
274 // while the first will call foo only once.
274 // while the first will call foo only once.
275 this.on('change', function() {
275 this.on('change', function() {
276 if (keys.some(this.hasChanged, this)) {
276 if (keys.some(this.hasChanged, this)) {
277 callback.apply(context);
277 callback.apply(context);
278 }
278 }
279 }, this);
279 }, this);
280
280
281 },
281 },
282 });
282 });
283 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
283 widgetmanager.WidgetManager.register_widget_model('WidgetModel', WidgetModel);
284
284
285
285
286 var WidgetView = Backbone.View.extend({
286 var WidgetView = Backbone.View.extend({
287 initialize: function(parameters) {
287 initialize: function(parameters) {
288 // Public constructor.
288 // Public constructor.
289 this.model.on('change',this.update,this);
289 this.model.on('change',this.update,this);
290 this.options = parameters.options;
290 this.options = parameters.options;
291 this.child_model_views = {};
291 this.child_model_views = {};
292 this.child_views = {};
292 this.child_views = {};
293 this.model.views.push(this);
293 this.model.views.push(this);
294 this.id = this.id || IPython.utils.uuid();
294 this.id = this.id || IPython.utils.uuid();
295 this.on('displayed', function() {
295 this.on('displayed', function() {
296 this.is_displayed = true;
296 this.is_displayed = true;
297 }, this);
297 }, this);
298 },
298 },
299
299
300 update: function(){
300 update: function(){
301 // Triggered on model change.
301 // Triggered on model change.
302 //
302 //
303 // Update view to be consistent with this.model
303 // Update view to be consistent with this.model
304 },
304 },
305
305
306 create_child_view: function(child_model, options) {
306 create_child_view: function(child_model, options) {
307 // Create and return a child view.
307 // Create and return a child view.
308 //
308 //
309 // -given a model and (optionally) a view name if the view name is
309 // -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.
310 // not given, it defaults to the model's default view attribute.
311
311
312 // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
312 // 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
313 // it would be great to have the widget manager add the cell metadata
314 // to the subview without having to add it here.
314 // to the subview without having to add it here.
315 options = $.extend({ parent: this }, options || {});
315 options = $.extend({ parent: this }, options || {});
316 var child_view = this.model.widget_manager.create_view(child_model, options, this);
316 var child_view = this.model.widget_manager.create_view(child_model, options, this);
317
317
318 // Associate the view id with the model id.
318 // Associate the view id with the model id.
319 if (this.child_model_views[child_model.id] === undefined) {
319 if (this.child_model_views[child_model.id] === undefined) {
320 this.child_model_views[child_model.id] = [];
320 this.child_model_views[child_model.id] = [];
321 }
321 }
322 this.child_model_views[child_model.id].push(child_view.id);
322 this.child_model_views[child_model.id].push(child_view.id);
323
323
324 // Remember the view by id.
324 // Remember the view by id.
325 this.child_views[child_view.id] = child_view;
325 this.child_views[child_view.id] = child_view;
326 return child_view;
326 return child_view;
327 },
327 },
328
328
329 pop_child_view: function(child_model) {
329 pop_child_view: function(child_model) {
330 // Delete a child view that was previously created using create_child_view.
330 // Delete a child view that was previously created using create_child_view.
331 var view_ids = this.child_model_views[child_model.id];
331 var view_ids = this.child_model_views[child_model.id];
332 if (view_ids !== undefined) {
332 if (view_ids !== undefined) {
333
333
334 // Only delete the first view in the list.
334 // Only delete the first view in the list.
335 var view_id = view_ids[0];
335 var view_id = view_ids[0];
336 var view = this.child_views[view_id];
336 var view = this.child_views[view_id];
337 delete this.child_views[view_id];
337 delete this.child_views[view_id];
338 view_ids.splice(0,1);
338 view_ids.splice(0,1);
339 child_model.views.pop(view);
339 child_model.views.pop(view);
340
340
341 // Remove the view list specific to this model if it is empty.
341 // Remove the view list specific to this model if it is empty.
342 if (view_ids.length === 0) {
342 if (view_ids.length === 0) {
343 delete this.child_model_views[child_model.id];
343 delete this.child_model_views[child_model.id];
344 }
344 }
345 return view;
345 return view;
346 }
346 }
347 return null;
347 return null;
348 },
348 },
349
349
350 do_diff: function(old_list, new_list, removed_callback, added_callback) {
350 do_diff: function(old_list, new_list, removed_callback, added_callback) {
351 // Difference a changed list and call remove and add callbacks for
351 // Difference a changed list and call remove and add callbacks for
352 // each removed and added item in the new list.
352 // each removed and added item in the new list.
353 //
353 //
354 // Parameters
354 // Parameters
355 // ----------
355 // ----------
356 // old_list : array
356 // old_list : array
357 // new_list : array
357 // new_list : array
358 // removed_callback : Callback(item)
358 // removed_callback : Callback(item)
359 // Callback that is called for each item removed.
359 // Callback that is called for each item removed.
360 // added_callback : Callback(item)
360 // added_callback : Callback(item)
361 // Callback that is called for each item added.
361 // Callback that is called for each item added.
362
362
363 // Walk the lists until an unequal entry is found.
363 // Walk the lists until an unequal entry is found.
364 var i;
364 var i;
365 for (i = 0; i < new_list.length; i++) {
365 for (i = 0; i < new_list.length; i++) {
366 if (i >= old_list.length || new_list[i] !== old_list[i]) {
366 if (i >= old_list.length || new_list[i] !== old_list[i]) {
367 break;
367 break;
368 }
368 }
369 }
369 }
370
370
371 // Remove the non-matching items from the old list.
371 // Remove the non-matching items from the old list.
372 for (var j = i; j < old_list.length; j++) {
372 for (var j = i; j < old_list.length; j++) {
373 removed_callback(old_list[j]);
373 removed_callback(old_list[j]);
374 }
374 }
375
375
376 // Add the rest of the new list items.
376 // Add the rest of the new list items.
377 for (; i < new_list.length; i++) {
377 for (; i < new_list.length; i++) {
378 added_callback(new_list[i]);
378 added_callback(new_list[i]);
379 }
379 }
380 },
380 },
381
381
382 callbacks: function(){
382 callbacks: function(){
383 // Create msg callbacks for a comm msg.
383 // Create msg callbacks for a comm msg.
384 return this.model.callbacks(this);
384 return this.model.callbacks(this);
385 },
385 },
386
386
387 render: function(){
387 render: function(){
388 // Render the view.
388 // Render the view.
389 //
389 //
390 // By default, this is only called the first time the view is created
390 // By default, this is only called the first time the view is created
391 },
391 },
392
392
393 show: function(){
393 show: function(){
394 // Show the widget-area
394 // Show the widget-area
395 if (this.options && this.options.cell &&
395 if (this.options && this.options.cell &&
396 this.options.cell.widget_area !== undefined) {
396 this.options.cell.widget_area !== undefined) {
397 this.options.cell.widget_area.show();
397 this.options.cell.widget_area.show();
398 }
398 }
399 },
399 },
400
400
401 send: function (content) {
401 send: function (content) {
402 // Send a custom msg associated with this view.
402 // Send a custom msg associated with this view.
403 this.model.send(content, this.callbacks());
403 this.model.send(content, this.callbacks());
404 },
404 },
405
405
406 touch: function () {
406 touch: function () {
407 this.model.save_changes(this.callbacks());
407 this.model.save_changes(this.callbacks());
408 },
408 },
409
409
410 after_displayed: function (callback, context) {
410 after_displayed: function (callback, context) {
411 // Calls the callback right away is the view is already displayed
411 // Calls the callback right away is the view is already displayed
412 // otherwise, register the callback to the 'displayed' event.
412 // otherwise, register the callback to the 'displayed' event.
413 if (this.is_displayed) {
413 if (this.is_displayed) {
414 callback.apply(context);
414 callback.apply(context);
415 } else {
415 } else {
416 this.on('displayed', callback, context);
416 this.on('displayed', callback, context);
417 }
417 }
418 },
418 },
419 });
419 });
420
420
421
421
422 var DOMWidgetView = WidgetView.extend({
422 var DOMWidgetView = WidgetView.extend({
423 initialize: function (parameters) {
423 initialize: function (parameters) {
424 // Public constructor
424 // Public constructor
425 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
425 DOMWidgetView.__super__.initialize.apply(this, [parameters]);
426 this.on('displayed', this.show, this);
426 this.on('displayed', this.show, this);
427 this.after_displayed(function() {
427 this.after_displayed(function() {
428 this.update_visible(this.model, this.model.get("visible"));
428 this.update_visible(this.model, this.model.get("visible"));
429 this.update_css(this.model, this.model.get("_css"));
429 this.update_css(this.model, this.model.get("_css"));
430 }, this);
430 }, this);
431 this.model.on('msg:custom', this.on_msg, this);
431 this.model.on('msg:custom', this.on_msg, this);
432 this.model.on('change:visible', this.update_visible, this);
432 this.model.on('change:visible', this.update_visible, this);
433 this.model.on('change:_css', this.update_css, this);
433 this.model.on('change:_css', this.update_css, this);
434 },
434 },
435
435
436 on_msg: function(msg) {
436 on_msg: function(msg) {
437 // Handle DOM specific msgs.
437 // Handle DOM specific msgs.
438 switch(msg.msg_type) {
438 switch(msg.msg_type) {
439 case 'add_class':
439 case 'add_class':
440 this.add_class(msg.selector, msg.class_list);
440 this.add_class(msg.selector, msg.class_list);
441 break;
441 break;
442 case 'remove_class':
442 case 'remove_class':
443 this.remove_class(msg.selector, msg.class_list);
443 this.remove_class(msg.selector, msg.class_list);
444 break;
444 break;
445 }
445 }
446 },
446 },
447
447
448 add_class: function (selector, class_list) {
448 add_class: function (selector, class_list) {
449 // Add a DOM class to an element.
449 // Add a DOM class to an element.
450 this._get_selector_element(selector).addClass(class_list);
450 this._get_selector_element(selector).addClass(class_list);
451 },
451 },
452
452
453 remove_class: function (selector, class_list) {
453 remove_class: function (selector, class_list) {
454 // Remove a DOM class from an element.
454 // Remove a DOM class from an element.
455 this._get_selector_element(selector).removeClass(class_list);
455 this._get_selector_element(selector).removeClass(class_list);
456 },
456 },
457
457
458 update_visible: function(model, value) {
458 update_visible: function(model, value) {
459 // Update visibility
459 // Update visibility
460 this.$el.toggle(value);
460 this.$el.toggle(value);
461 },
461 },
462
462
463 update_css: function (model, css) {
463 update_css: function (model, css) {
464 // Update the css styling of this view.
464 // Update the css styling of this view.
465 var e = this.$el;
465 var e = this.$el;
466 if (css === undefined) {return;}
466 if (css === undefined) {return;}
467 for (var i = 0; i < css.length; i++) {
467 for (var i = 0; i < css.length; i++) {
468 // Apply the css traits to all elements that match the selector.
468 // Apply the css traits to all elements that match the selector.
469 var selector = css[i][0];
469 var selector = css[i][0];
470 var elements = this._get_selector_element(selector);
470 var elements = this._get_selector_element(selector);
471 if (elements.length > 0) {
471 if (elements.length > 0) {
472 var trait_key = css[i][1];
472 var trait_key = css[i][1];
473 var trait_value = css[i][2];
473 var trait_value = css[i][2];
474 elements.css(trait_key ,trait_value);
474 elements.css(trait_key ,trait_value);
475 }
475 }
476 }
476 }
477 },
477 },
478
478
479 _get_selector_element: function (selector) {
479 _get_selector_element: function (selector) {
480 // Get the elements via the css selector.
480 // Get the elements via the css selector.
481 var elements;
481 var elements;
482 if (!selector) {
482 if (!selector) {
483 elements = this.$el;
483 elements = this.$el;
484 } else {
484 } else {
485 elements = this.$el.find(selector).addBack(selector);
485 elements = this.$el.find(selector).addBack(selector);
486 }
486 }
487 return elements;
487 return elements;
488 },
488 },
489 });
489 });
490
490
491 var widget = {
491 var widget = {
492 'WidgetModel': WidgetModel,
492 'WidgetModel': WidgetModel,
493 'WidgetView': WidgetView,
493 'WidgetView': WidgetView,
494 'DOMWidgetView': DOMWidgetView,
494 'DOMWidgetView': DOMWidgetView,
495 };
495 };
496
496
497 // For backwards compatability.
497 // For backwards compatability.
498 $.extend(IPython, widget);
498 $.extend(IPython, widget);
499
499
500 return widget;
500 return widget;
501 });
501 });
General Comments 0
You need to be logged in to leave comments. Login now