comment.js
3.54 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
define("portal/comment", ['utils', 'zepto', 'juicer'], function (_u) {
var comment = {
el: "#page-comment",
formdata: {},
isSend: false, // 区分点击的是cancel还是send
sending: false,
reset: function () {
var $el = $(this.el);
this.isSend = false;
this.sending = false;
this.formdata = {};
$el.find(".star").addClass("active");
$el.find("input").val("");
$el.find("textarea").val("");
$el.find(".send").removeClass("active");
},
bindEvent: function () {
var $el = $(this.el);
var that = this;
var _goBack = function () {
history.go(-1);
};
$el.on("click.cancel", '.cancel', _goBack).on("click.send", '.send', function () {
var $send = $(this);
var formdata = that.formdata;
if (!$send.hasClass("active") || that.sending) return;
formdata.content = that.utf16toEntities( $el.find("textarea").val() );
that.sending = true; // 防止重复提交评论
_u.ajax({
action: "saveComment",
data: formdata,
type: "post"
}, function () {
that.isSend = true;
_goBack();
});
}).on("click.star", ".star", function () { // 评分
var $star = $(this);
var index = $star.index();
that.formdata.score = index + 1;
$star.addClass("active");
$star.prevAll().addClass("active");
$star.nextAll().removeClass("active");
that.toggleSendBtn();
});
// 标题为必填
$el.find("input").on("input", function () {
var val = $(this).val();
that.formdata.title = val;
that.toggleSendBtn();
});
},
/**
* 用于把用utf16编码的字符转换成实体字符,以供后台存储
* @param {string} str 将要转换的字符串,其中含有utf16字符将被自动检出
* @return {string} 转换后的字符串,utf16字符将被转换成&#xxxx;形式的实体字符
*/
utf16toEntities: function (str) {
var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
str = str.replace(patt, function (char) {
var H, L, code;
if (char.length === 2) {
H = char.charCodeAt(0); // 取出高位
L = char.charCodeAt(1); // 取出低位
code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
return "&#" + code + ";";
} else {
return char;
}
});
return str;
},
toggleSendBtn: function () {
var formdata = this.formdata;
var isEnabled = formdata.title && formdata.score;
$(this.el).find(".send").toggleClass("active", !!isEnabled);
}
};
return {
init: function () {
comment.bindEvent();
},
reset: function (formdata) {
comment.reset();
comment.formdata = _u.strToJson(formdata, "&", "=");
comment.formdata.score = 5;
},
isSend: function () {
return comment.isSend;
}
};
});