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

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

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

var loading = false;

ellipsis.init();

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

        $.ajax({
            type: 'GET',
            url: '/guang/info/prise', //TODO:cancelPrise
            data: {
                id: $info.data('id')
            }
        }).then(function(data) {
            var code = data.code;

            if (code === 200) {
                $likeBtn.next('.like-count').text(data.data);
            } else if (code === 400) {
                tip.show('未登录');
            }
        }, function() {
            tip.show('网络断开连接了~');
        });
    });

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

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

    $infos.each(function() {
        var $this = $(this);

        $this.find('.info-title')[0].mlellipsis(2);
        $this.find('.info-text')[0].mlellipsis(2);
    });
}

/**
 * 资讯LoadMore
 */
function loadMore($container, opt) {
    var infosNum = $container.find('.guang-info').length;

    if (loading) {
        return;
    }

    loading = true;
    $.ajax({
        type: 'GET',
        url: '/infos/get',
        data: opt
    }).then(function(data) {
        var res,
            $newInfos;

        if (data.code === 200) {
            res = data.data;

            if (res.end) {
                opt.end = true;
            }

            $container.append(res.infos);
            $newInfos = $container.find('.guang-info:gt(' + (infosNum - 1) + ')');
            _setLazyLoadAndMellipsis($newInfos);

            opt.page++;
        }

        loading = false;
    });
}

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