info.js 2.84 KB
/**
 * 资讯相关API
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/10/10
 */

var $ = require('yoho.zepto'),
    ellipsis = require('mlellipsis'),
    lazyLoad = require('yoho.zeptolazyload');

var tip = require('../plugin/tip');

var $loadMoreInfo = $('#load-more-info');
var $loading = $(''),
    $noMore = $('');

var loading = false;

ellipsis.init();

if ($loadMoreInfo.length > 0) {
    $loading = $loadMoreInfo.children('.loading');
    $noMore = $loadMoreInfo.children('.no-more');
}

/**
 * 设置指定资讯项的Lazyload和文字截取
 * @params $infos 资讯项
 */
function setLazyLoadAndMellipsis($infos) {
    lazyLoad($infos.find('img.lazy'));

    $infos.each(function() {
        var $this = $(this),
            $title = $this.find('.info-title'),
            $text = $this.find('.info-text');

        $title[0].mlellipsis(2);
        $text[0].mlellipsis(2);
    });
}

/**
 * 初始化资讯列表事件绑定
 * @params $container 逛资讯列表容器
 */
function initInfosEvt($container) {
    $container.delegate('.like-btn', 'tap', function(e) {
        var $likeBtn = $(e.currentTarget),
            $info = $likeBtn.closest('.guang-info'),
            opt = 'ok';

        if ($likeBtn.hasClass('like')) {
            opt = 'cancel';
        }

        $.ajax({
            type: 'POST',
            url: '/guang/opt/praiseArticle',
            data: {
                id: $info.data('id'),
                opt: opt
            },
            success: function(data) {
                var code = data.code;

                if (code === 200) {
                    $likeBtn.next('.like-count').text(data.data);

                    //切换点赞状态
                    $likeBtn.toggleClass('like');
                }
            },
            error: function() {
                tip.show('网络断开连接了~');
            }
        });
    });

    setLazyLoadAndMellipsis($container.find('.guang-info'));
}

/**
 * 资讯LoadMore
 */
function loadMore($container, opt) {
    if (loading) {
        return;
    }

    if (opt.end) {
        return;
    }

    loading = true;
    $.ajax({
        type: 'GET',
        url: ' /guang/list/page',
        data: opt,
        success: function(data) {
            if (data === ' ') {
                opt.end = true;
                loading = false;

                //
                $loading.addClass('hide');
                $noMore.removeClass('hide');

                return;
            }
            $container.append(data);

            setLazyLoadAndMellipsis($container.find('.guang-info'));

            opt.page++;

            loading = false;
        },
        error: function() {
            tip.show('网络断开连接了~');
            loading = false;
        }
    });
}

exports.initInfosEvt = initInfosEvt;
exports.setLazyLoadAndMellipsis = setLazyLoadAndMellipsis;
exports.loadMore = loadMore;