img-preview.js 2.29 KB
/**
 * 图片预览
 * @author: liuchuanyang<chuanyang.liu@yoho.cn>
 * @date: 2016/10/27
 */

var $ = require('yoho-jquery'),
    Handlebars = require('yoho-handlebars'),
    Dialog = require('./dialog').Dialog;

var tpl = '<div class="toolbar">' +
              '<a class="preview-route-left" href="javascript:void(0);"><i class="iconfont">&#xe639;</i>向左转</a>' +
              '<a class="preview-route-right" href="javascript:void(0);"><i class="iconfont">&#xe63a;</i>向右转</a>' +
          '</div>' +
          '<div class="preview-body"><img /></div>';

var tplFn = Handlebars.compile(tpl);

function ImgPreview(url, opt) {
    var that = this;

    var option = {
        content: tplFn(),
        className: 'img-preview-dialog'
    };

    Dialog.call(this, $.extend({}, opt || {}, option));

    this._data = {
        url: url,
        rotate: 0
    };

    this.$previewBody = this.$el.find('.preview-body');
    this.$img = this.$previewBody.find('img');
    this.$toolbar = this.$el.find('.toolbar');

    this.$toolbar.on('click', '.preview-route-left', function() {
        that.rotateLeft();
    });

    this.$toolbar.on('click', '.preview-route-right', function() {
        that.rotateRight();
    });

    if (this.$mask) {
        this.$mask.css({
            width: 'auto',
            height: 'auto'
        });
        this.$mask.on('click', function() {
            that.close();
        });
    }
}

ImgPreview.prototype = new Dialog({
    inherit: true
});

ImgPreview.prototype.close = function() {
    this.$mask && this.$mask.addClass('hide');
    this.$el.addClass('hide');
    $('body').removeClass('dialog-open');
};


ImgPreview.prototype.preview = function(url) {

    if (url) {
        this._data.url = url;
    }

    this._data.rotate = 0;
    this.$img.attr('src', this._data.url);
    this.refresh();

    this.show();
    $('body').addClass('dialog-open');
};

ImgPreview.prototype.refresh = function() {
    this.$img.css('transform', 'rotate(' + this._data.rotate + 'deg)');
};

ImgPreview.prototype.rotateLeft = function() {
    this._data.rotate = this._data.rotate - 90;
    this.refresh();
};

ImgPreview.prototype.rotateRight = function() {
    this._data.rotate = this._data.rotate + 90;
    this.refresh();
};

ImgPreview.prototype.constructor = ImgPreview;
module.exports = ImgPreview;