util.js 2.48 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(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]
     */
    refreshCart: function(data, callback) {
        var template;

        // 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;
            } else {
                console.error('multiplication needs two number parameters');
            }
        });

        hbs.registerHelper('isEqual', function(v1, v2, options) {
            if (v1 === v2) {
                return options.fn(this);
            }
            return options.inverse(this);
        });

        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;