-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHotEditItemView.js
55 lines (55 loc) · 1.9 KB
/
HotEditItemView.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// HotEditItemView.js
define([
'underscore',
'jquery',
'backbone',
'marionette'
], function(_,$,Backbone,Marionette){
var parent = Backbone.Marionette.ItemView.prototype;
return Backbone.Marionette.ItemView.extend({
constructor: function() {
this.events = this.events || {};
_.extend(this.events, this.hotEditEvents);
parent.constructor.apply(this, arguments);
},
hotEditEvents: {
'click .hot-edit': 'hoteditStart',
'keypress .hot-edit': function(e){
if(e.keyCode === 13 && !e.shiftKey) this.hoteditFinish(e);
}
},
nestedExtend: function(target, fields, value){
var head = fields.shift();
if (fields.length === 0){
target[head] = value;
return target;
}
target[head] = this.nestedExtend(target[head], fields, value);
return target;
},
hoteditStart: function(e){
e.preventDefault();
var hotEdit = $(e.target).parent();
if (!hotEdit.hasClass("active")) {
value = $(e.target).html().replace(/^\s+/, '').replace(/\s+$/, '');
hotEdit.html("<input type='text' value='" + value + "'>");
hotEdit.addClass("active");
hotEdit.find("input").focus();
var finish = _.bind(this.hoteditFinish, this);
hotEdit.on("focusout", finish);
}
},
hoteditFinish: function(e){
e.preventDefault();
var hotEdit = $(e.target).parent();
value = $(e.target).val().replace(/^\s+/, '').replace(/\s+$/, '');
var targetField = hotEdit.attr('hot-edit-field');
var obj = this.nestedExtend(_.clone(this.model.attributes), targetField.split('.'), value);
targetField = targetField.split('.').shift();
this.model.save(_.pick(obj, targetField), {patch: true});
hotEdit.off("focusout");
hotEdit.removeClass("active");
hotEdit.html("<p> " + value + "</p>");
},
});
});