add.js 2.52 KB
/*
 *@time: 2016/1/29
 *@author: chenglong
 */

var $ = require('jquery');
var edit = require('../common/edit');
var Handlebars = require('yoho.handlebars');
var dropDown = require('../common/dropDown');

var selectOption =
    '{{# data}}' +
        '<option value="{{id}}">{{sortName}}</option>' +
    '{{/ data}}';

var optionStr = Handlebars.compile(selectOption);

function getAllSort(callback) {
    $.ajax({
        url: '/product/class/queryAllProductSortList',
        type: 'POST',
        dataType: 'json'
    }).then(function (d) {

        var firstSort = [],
            data = d.data.data,
            sortLen = data.length,
            i;

        for (i = 0; i < sortLen; i++) {
            if (!data[i].child) {
                firstSort.push(data[i]);
            }
        }

        callback(firstSort);
    });
}

function getChildSort(id, callback) {
    $.ajax({
        url: '/product/class/queryProductSortList',
        type: 'POST',
        dataType: 'json',
        data: {
            param: id
        }
    }).then(function (d) {

        callback(d);
    });
}


exports.init = function () {

    new dropDown({
        el:'.level-select'
    });

    // 页面初始化渲染一级菜单
    getAllSort(function (data) {

        $('#parentSortId').after(optionStr({
            data: data
        }));

    });

    // 选择一\二级菜单时渲染二\三级菜单
    $('.level-select').change(function () {

        var id = $(this).val();
        var thisChild = $(this).attr('data-child');

        if (!thisChild) {
            return;
        }


        getChildSort(id, function (data) {

            $('#' + thisChild).find('option:first').after(optionStr(data.data));

        });
    });

    // 添加品类表单验证
    var newClassVerification = new edit("#new-class-form");

    $(".new-class-btn").click(function(){

        var id = $(this).attr('data-id');
        var postUrl;

        if (!!id) {
            postUrl = '/product/updateProductSort'
        } else {
            postUrl = $("#new-class-form").attr("action");
        }

        newClassVerification.submit(postUrl, function(option,that) {
            option.success=function(res){

                console.log(res);

                window.location.href = '/product/class/index';
            };
            option.error=function(res){

                console.log('error');
            }
        });
        return false;
    });
};