jQuery Plugin Development Example

(function( $ ){
	var settings = {
        type: 'remain', 
        onUpdate: null
    }

    var $c = null;
    var member_id = 0;
    var parent_id = 0;

    var methods = {
        init : function(options) {
        	settings = $.extend(settings, options);
            //console.log(settings);

            $c = $('#storedValueModal');

            /*
            Because this plugin will be initialized everytime datatable is loaded(refresh), so click listener should be unbind first.
            */
            $c.find('.bt_submit').unbind('click').on('click', function(e){
                e.preventDefault();
                if(settings.type == 'remain'){
                    update_points();
                }else if(settings.type == 'init_quota'){
                    update_quota();
                }
            });

            $c.find('.bt_search').unbind('click').on('click', function(e){
                e.preventDefault();
                get_list();
            });

            $c.find('.quick_search a').unbind('click').on('click', function(e){
                e.preventDefault();
                var $this = $(this);

                $c.find('.quick_search a.active').removeClass('active');
                $this.addClass('active');

                var $f = $c.find('[name="from"]');
                var $t = $c.find('[name="to"]');

                var today = moment();
                if($this.hasClass('today')){
                    $f.val(today.format('MM/DD/YYYY'));
                    $t.val(today.format('MM/DD/YYYY'));
                }else if($this.hasClass('yest')){
                    $f.val(today.clone().add(-1, 'days').format('MM/DD/YYYY'));
                    $t.val(today.clone().add(-1, 'days').format('MM/DD/YYYY'));
                }else if($this.hasClass('this_w')){
                    $f.val(today.clone().add(-7, 'days').format('MM/DD/YYYY'));
                    $t.val(today.format('MM/DD/YYYY'));
                }else if($this.hasClass('last_w')){
                    $f.val(today.clone().add(-14, 'days').format('MM/DD/YYYY'));
                    $t.val(today.clone().add(-7, 'days').format('MM/DD/YYYY'));
                }else if($this.hasClass('this_m')){
                    $f.val(today.clone().add(-30, 'days').format('MM/DD/YYYY'));
                    $t.val(today.format('MM/DD/YYYY'));
                }

                $c.find('.bt_search').trigger('click');
            });

        	return this.each( function() {
			    var $this = $(this);
			    
                $this.on('click', function(e){
                    e.preventDefault();

                    member_id = $this.data('id');
                    parent_id = $this.data('parent');

                    if($this.hasClass('change_remain') == true){
                        settings.type = 'remain';

                        $c.find('.modal_label').html('[帳戶餘額]儲值');
                        $c.find('.point_label').html('帳戶餘額');
                        $c.find('.bt_submit').html('儲值');
                    }else if($this.hasClass('change_quota') == true){
                        settings.type = 'init_quota';

                        $c.find('.modal_label').html('[預設額度]增減');
                        $c.find('.point_label').html('預設額度');
                        $c.find('.bt_submit').html('增減');
                    }

                    show();
                });
			});
        }
    };

    function show(){
        //console.log('show');
        refresh();
        $c.modal();
    }

    function refresh(){
        //console.log('refresh');
        clear();
        get_point_info();
        $c.find('.quick_search .today').trigger('click');
    }

    function clear(){
        set_value('points', '0', $c);
    }

    function get_point_info(callback){
        var params = {
            member_id: member_id
        };
        //console.log(params);

        $.get(base_url + 'admin/ajax/point_info', params, function(data){
            if(typeof data.status == 'undefined'){
                alert(data);
            }else if(data.status == 'fail'){
                alert(data.message);
            }else{
                //console.log(data.data);
                if(typeof callback == 'function'){
                    callback.call(null, data.data);
                }

                fill_form(data.data);
            }
        });
    }

    function fill_form(data){
        $c.find('.member_name').html(data.member.name);

        $c.find('.m_quota').html(data.member.init);
        $c.find('.m_remain').html(data.member.remain);
        $c.find('.p_remain').html(data.parent.remain);
        $c.find('.available').html(data.parent.remain);
    } 

    function get_list(){
        var params = {
            member_id: member_id, 
            from: get_value('from', $c), 
            to: get_value('to', $c)
        };
        //console.log(params);

        $.get(base_url + 'admin/ajax/point_logs', params, function(data){
            if(typeof data.status == 'undefined'){
                alert(data);
            }else if(data.status == 'fail'){
                alert(data.message);
            }else{
                if(typeof callback == 'function'){
                    callback.call(null, data.data, data.extra);
                }

                fill_table(data.data, data.extra);
            }
        });
    }

    function fill_table(data, extra){
        var $t = $c.find('.history_table');
        var $body = $t.find('tbody');
        $body.children().remove();

        for(var i = 0; i < data.length; i++){
            var item = data[i];
            $body.append(
                '<tr>' + 
                    '<td>' + item.id + '</td>' + 
                    '<td>' + get_status(item) + '</td>' + 
                    '<td>' + item.member_name + '</td>' + 
                    '<td>' + item.point + '</td>' + 
                    '<td>' + item.type_name + '</td>' + 
                    '<td>' + item.created_time + '</td>' + 
                    '<td>' + item.note + '</td>' + 
                    '<td>' + item.ip + '</td>' + 
                '</tr>'
            );
        }

        $t.find('tfoot .total').html(extra.total);
    }

    function get_status(item){
        var color_class = 'st-success';
        if(item.editor_status == 2){
            color_class = 'st-danger';
        }else if(item.editor_status == 3){
            color_class = 'st-warning';
        }

        var str = '<div class="status-group">' + 
            '<span class="status ' + color_class + '"></span><span class="st-text">' + item.editor_name + '</span></div>';
        return str;
    }

    function update_quota(){
        var params = {
            member_id: member_id, 
            points: get_value('points', $c), 
            type: 10, 
            note: '上級增減'
        };
        //console.log(params);
        //return;

        $.post(base_url + 'admin/ajax/points', params, function(data){
            if(typeof data.status == 'undefined'){
                alert(data);
            }else if(data.status == 'fail'){
                alert(data.message);
            }else{
                //console.log(data);
                alert('增減成功');
                refresh();

                //Refresh main table
                datatable.refresh();

                if(typeof settings.onUpdate == 'function'){
                    settings.onUpdate.call(this);
                }
            }
        });
    }

    function update_points(){
        var params = {
            member_id: member_id, 
            points: get_value('points', $c), 
            type: 11, 
            note: '上級儲值'
        };
        //console.log(params);
        //return;

        $.post(base_url + 'admin/ajax/points', params, function(data){
            if(typeof data.status == 'undefined'){
                alert(data);
            }else if(data.status == 'fail'){
                alert(data.message);
            }else{
                //console.log(data);
                alert('儲值成功');
                refresh();

                if(typeof settings.onUpdate == 'function'){
                    settings.onUpdate.call(this);
                }
            }
        });
    }

    $.fn.changePoints = function(methodOrOptions) {
    	//If methodOrOptions is a method name
        if ( methods[methodOrOptions] ) {
            return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
            // Default to "init"
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  methodOrOptions + ' does not exist.' );
        }    
    };


})( jQuery );

Reference:

  1. https://stackoverflow.com/questions/1117086/how-to-create-a-jquery-plugin-with-methods