util.js 2.92 KB
/**
 * [购物车] 工具库
 * @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;