diliCascade.js 11.8 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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
/**
 * 动态select级联
 * @param conf
 * @constructor
 */

/**
 * 实体类
 * @param url
 * @constructor
 */
function Category(conf) {
    var conf = conf;
    var self = this;
    var url = conf.url;

    //选择一个数据, 如果有子数据, 则把子数据展示出来
    self.load = function (param) {
        self.trigger("model.startLoad", param);
        var path = riot.render(url, param);

        try{
            $.ajax({
                url: path
                , dataType: conf.urlType, success: function(data) {
//                    handleLoad(param, data);
                    try{
                        if( param.step == 0){
                            if(data.length == 0) {
                                throw "没有找到数据!";
                            }
                        }
                        if(data.length > 0){
                            self.trigger("model.load", param, data);
                        } else {
                            conf.leafHandle();
                            self.trigger("model.loadNull", param, data);
                        }
                    } catch (e){
                        self.trigger("model.loadError", param);
                    }
                }
                , error: function(data){
                    self.trigger("model.loadError", param);
                }
            });
        } catch (e){
            self.trigger("model.loadError", param);
            console.log("model.loadError")
        }
    };


    self.init = function(obj){
        if(!(conf.val && conf.val != null && conf.val != "" && conf.index == -1)){
            return ;
        }
        var path = riot.render(conf.peggingUrl, {"pid":conf.val});
        if(path == null || path == "") {
            return;
        }
        $.ajax({
            url: path
            , dataType: conf.urlType, success: function(data) {
                if(conf.peggingExtract){
                    conf.vals = conf.peggingExtract(data);
                } else {
                    conf.vals = data;
                }
                conf.index = 0;
                self.trigger("model.init", obj);
            }
            , error: function(data){
                self.trigger("model.loadError", obj);
            }
        });

    };

    riot.observable(self);
}

/**
 * 视图类
 * @param root
 * @param valName
 * @constructor
 */
function View(conf) {
    var conf = conf;
    var root = $(conf.root), valName = conf.name;
    var self = this;
    self.root = $(root);


    self.tmpl = "<div class='itemsPanel' style='display: inline-block;'></div><div class='msgPanel' style='display: inline-block;'></div>"

    self.tmplSel = "<select class='categoryItem' data-pid='{pid}'>" +
        "<option value=''>请选择</option>" +
        "</select>";
    self.tmplOpt = "<option value='{val}' data-has_child='{hasChild}'>{name}</option>";
    self.tmplHidden = "<input type='hidden' class = 'categoryItemVal' value='' name='{name}'>";

    /**
     * 数据初始化
     */
    self.init = function(){
        var view = $(riot.render(self.tmpl, conf.hint));
        self.root.append(view);
        self.itemPanel = self.root.find(".itemsPanel");
        self.msgPanel = self.root.find(".msgPanel");
    };

    /**
     * 显示新的列表
     * @param list
     */
    self.show = function (obj, list) {
        var sel = $(riot.render(self.tmplSel, obj));
        //添加校验
        if (conf.validate) {
            for (var i in conf.validate) {
                sel.attr(i, conf.validate[i]);
            }
        }
        for (var i in list) {
            var item = list[i];
            var obj = {};
            if (conf.extract) {
                obj = conf.extract(item);
            }
            var option = riot.render(self.tmplOpt, obj);
            sel.append(option);
        }
        self.itemPanel.append(sel);
        sel.attr("name", conf.name + self.itemPanel.find("select").size());
        var t = {};
        t.sel = sel;
        self.trigger("view.show", t);
    };

    /**
     * 正在加载数据
     */
    self.loading = function(){
        var loadTmpl = "<div class=''>{loading}</div>";
        var item = $(riot.render(loadTmpl, conf.hint));
        self.msgPanel.html(item);
    };

    self.clearMsg = function(){
        self.msgPanel.html("");
    };

    self.loadError = function (obj) {
        var loadTmpl = "<div class='errorMsg'>系统错误,请<a href='javascript:;' class='reload'>重新获取数据</a>!</div>";
        var item = $(riot.render(loadTmpl, conf.hint));
        self.msgPanel.html(item);
        var btn = self.msgPanel.find(".reload");
        btn.data("loadParam", obj);
        btn.click(function(){
            var re = $(this);
            var obj = re.data("loadParam");
            self.trigger("view.reloadRequest", obj);
        });
    };

    /**
     * 重新加载
     * @param obj
     */
    self.reload = function(obj){
        if(!(conf.vals && conf.vals.length > 0 && conf.vals.length > conf.index)){
            return;
        }
        var t = obj.sel.find("[value=" + conf.vals[conf.index] + "]");
        if(t.size() == 1) {
            obj.sel.val(conf.vals[conf.index]);
            conf.index ++;
            obj.sel.change();
            return;
        }
        conf.index = -1;
    };

    /**
     * 清除选中项后面的数据
     * @param obj
     */
    self.clear = function (obj) {
        var t = $(obj.sel);
        if(t.size() > 0){
            while(!(t.parent().is(self.itemPanel))){
                t = t.parent();
            }
            t.nextAll().remove();
        }
    }

    /**
     * 清除所有的选择
     */
    self.clearAll = function(){
        var first = self.itemPanel.find(".categoryItem").get(0);
        first = $(first);
        first.get(0).selectedIndex = 0;
        first.change();
        self.itemPanel.find(".categoryItemVal").remove();
    }

    /**
     * 刷新组件的值
     * @param obj
     */
    self.refreshVal = function (obj) {
        var val = self.itemPanel.find(".categoryItemVal");
        if (val == undefined || val == null || val.size() <= 0) {
            val = $(riot.render(self.tmplHidden, {name: valName}));
            self.itemPanel.prepend(val);
        }

        if (obj.hasChild == undefined || obj.hasChild == null || obj.hasChild == true) {
            val.val("");
            val.attr("data-cate-txt", "");
            return;
        }
        val.val(obj.pid);
        var txt = "";
        var first = true;
        self.itemPanel.find("select").each(function(){
            var item = $(this).find("option:selected");
            if(item.val() == ""){
                return;
            }
            if(first){
                first = false;
            } else {
                txt += conf.txtArrows
            }
            txt += item.text();
            val.attr("data-cate-txt", txt);
        });
    };

    /**
     * 监听改变事件
     */

    self.bind = function () {
        self.itemPanel.find(".categoryItem").unbind("change");
        self.itemPanel.find(".categoryItem").bind("change", function () {
            //    $(self.itemPanel.selector + " .categoryItem").live("change", function () {
            var sel = $(this);
            var item = sel.find("option:selected");
            var obj = {};
            obj.sel = sel;
            obj.hasChild = item.data("has_child");
            obj.val = sel.val();
            obj.text = item.text();
            obj.pid = obj.val;

            if (obj.val == undefined || obj.val == null || obj.val == "") {
                self.trigger("view.selectNull", obj)
                return;
            }

            self.trigger("view.select", obj);
        });
    };

    riot.observable(self);
    self.init();
}

/**
 * 控制器类
 * @param conf
 * @constructor
 */
function Controller(conf) {
    var conf = conf;
    var self = this;
    var model = new Category(conf);
//    var view = new View($(conf.root), conf.name);
    var view = new View(conf);
    /**
     * 监听事件
     */
    view.on("view.select", function (obj) {
        if(obj.hasChild == undefined || obj.hasChild == null || obj.hasChild == true || obj.hasChild == ""){
            model.load(obj);
        }
        view.refreshVal(obj);
    });
    //选择空
    view.on("view.selectNull", function (obj) {
        view.clear(obj);
        view.refreshVal(obj);
    });
    //显示内容
    view.on("view.show", function (obj) {
        view.bind();
        view.reload(obj);
        model.init(obj);
    });
    //重新加载请求
    view.on("view.reloadRequest", function(obj){
        model.load(obj);
    });
    //开始加载
    model.on("model.startLoad", function(obj){
        view.loading(obj);
    });
    //加载成功
    model.on("model.load", function (obj, list) {
        view.clearMsg();
        view.clear(obj);
        view.show(obj, list);
    });
    //加载失败
    model.on("model.loadError", function(obj){
        view.loadError(obj);
    });
    //没有子结点
    model.on("model.loadNull", function (obj) {
        view.clearMsg();
        view.clear(obj);
        view.refreshVal(obj);
    });
    //
    model.on("model.init", function (obj) {
        view.reload(obj);
    });

    self.clearAll = function(){
        view.clearAll();
    }
    model.load({pid: "0", step: 0});
}


/**
 * 创建插件
 */
(function ($) {
    //配置
    var config = {
        url: ""   //下一级查询的URL
        , peggingUrl: ""    //反查父级的URL
        , urlType:"jsonp"   //URL类型, 支持json, jsonp
        , root: "#productCategory"
        , name: ""      //选中值
        , validate: {} //validate校验
        , vals:[]       //默认值
        , val:""        //默认值最后一级
        , index : -1    //默认值的所引, 不可配置
        , txtArrows: "" //文本间的间隔符
        //转换, 将各个不同的类型转换成指定结构的JSON
        , extract: function(item){
            return {"name": item.regionName, "val": item.regionId, "hasChild": item.hasChild}
        }
        //反查转换, 转换成数组
        , peggingExtract: function (data){
            return data;
        }
        //选择叶子节点时出发
        , leafHandle: function(){}
        //提示
        , hint: {
            loading: "<img src='http://static.nong12.com/static/common/images/i/dili_ld.gif' style='width: 15px;vertical-align: middle;'>"
        }
    };

    var cityConf = {
//        url: "http://192.168.1.204/api/city/getCityJsonpList.do?parentId={pid}"
//        , peggingUrl: "http://192.168.1.204/api/city/getParentCityJsonpList.do?cityId={pid}"
        url: window.DiliPath.userPath + "/api/city/getCityJsonpList.do?parentId={pid}"
        , peggingUrl: window.DiliPath.userPath + "/api/city/getParentCityJsonpList.do?cityId={pid}"
        , urlType:"jsonp" //json或者jsonp
        , extract: function(item){
            return {"name": item.regionName, "val": item.regionId, "hasChild": item.hasChild}
        }
        //反查转换, 转换成数组
        , peggingExtract: function (data){
            var vals = new Array();
            for (var i in data){
                var item = data[i];
                vals.unshift(item.regionId);
            }
            return vals;
        }
    };

    var cateConf = {
        url: "http://user.nong12.com/common/nextcategory.do?pid={pid}"
        , urlType:"jsonp"
        , txtArrows:  "--&gt;"
        , extract: function(item){
            return {"name": item.cname, "val": item.cid, "hasChild": item.hasChild}
        }
    };

    $.fn.diliCity = function (cfg) {
        cfg.root = $(this);
        var c = $.extend(true, {}, config, cityConf, cfg);
        var cate = new Controller(c);
        return cate;
    };
    $.fn.diliCategory = function (cfg) {
        cfg.root = $(this);
        var c = $.extend(true, {}, config, cateConf, cfg);
        var cate = new Controller(c);
        return cate;
    };
})(jQuery)