util.js
2.92 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
/**
* [购物车] 工具库
* @author: jinhu.dong<jinhu.dong@yoho.cn>
* @date: 2016/07/11
* @module shopping/util
*/
var dialog = require('../../plugins/dialog');
var _alert = dialog.Alert;
var hbs = require('yoho-handlebars');
var Util = {
/*
* ajax请求封装
* @function [ajax]
* @params { Object } options ajax请求参数
*/
ajax: function(options) {
$.ajax({
type: options.type || 'GET',
url: options.url,
data: options.data || {},
dataType: 'json'
}).done(function(res) {
if (options.success && res.code === 200) {
options.success(res);
} else {
new _alert(res.message).show();
}
}).fail(function() {
if (options.fail) {
options.fail();
} else {
new _alert('网络异常,稍后请重试').show();
}
});
},
/*
* 根据服务端JSON,刷新购物车信息
* @function [refreshCart]
* @params { Object } data 最新购物车数据
* @params { Function } callback 购物车刷新后回调
*/
refreshCart: function(data, callback) {
var template;
if (!data.hasGoods) {
$('#cart_content').html($('#empty-cart-tpl').html());
return;
}
// helpers start
hbs.registerHelper('multiple', function(num1, num2) {
num1 = typeof num1 === 'number' ? num1 : parseFloat(num1, 10);
num2 = typeof num2 === 'number' ? num2 : parseFloat(num2, 10);
if (num1 && num2) {
return num1 * num2;
}
});
hbs.registerHelper('isEqual', function(v1, v2, options) {
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
hbs.registerHelper('round', function(num, fixedNum) {
num = typeof num === 'number' ? num : parseFloat(num, 10);
return num.toFixed(fixedNum);
});
hbs.registerHelper('showStorage', function(leftNumber) {
leftNumber = typeof num1 === 'number' ? leftNumber : parseFloat(leftNumber, 10);
if (leftNumber <= 3 && leftNumber >= 0) {
return '仅剩' + leftNumber + '件';
} else if (leftNumber < 0) {
return '库存不足';
}
});
hbs.registerHelper('image', function(url, width, height, mode) {
mode = parseInt(mode, 10) ? mode : 2;
url = url || '';
return url.replace(/{width}/g, width).replace(/{height}/g, height).replace(/{mode}/g, mode);
});
// helpers end
template = hbs.compile($('#cart-content-tpl').html());
$('#cart_content').html(template(data));
if (callback) {
return callback();
}
}
};
module.exports = Util;