如何在backbone.view.js中定义全局变量?

时间:2015-11-12 08:17:29

标签: backbone.js

如何将全局变量定义为backbone.view.js。还想知道如何将此varibale附加到函数。目的是创建一个对象并将服务器端作为json格式传递。我尝试定义如下代码,但它显示错误。这是我的view.js文件。

var IrWidgetView = WidgetView.extend({
  //var IreditorObject = IreditorObject || {}; 
    initialize: function (opts) {
        // Inherits parent method.
        WidgetView.prototype.initialize.call(this, opts);
        this.$fileDrop = null;

         this.IreditorObject = IreditorObject || {}; 
         IreditorObject.data = {};
        IreditorObject.data.imgContainer = [];


        this.self = this;
        this.bindEvents(true);
        // Browse server section.
        this.browseButton = null;
        this.browsevButton = null;
        this.browseFileText = null;
        this.$rotatorDeg = $('#rotate-angle-' + this.cid);
        this.$irContainer = $('<div class="ircontainer"></div>').appendTo(this.$el);
        var ireditorObject = ireditorObject || {};
        if (this.model.get('irlink')) {
            this.$irContainer.html(this.model.get('irlink'));
        }

        if (this.model.get('irPath')) {
            var irpath = this.model.get('irPath');
            var irCnt = '<iframe style="border:none;" class="iframe-wrap" src=' + irpath + '></iframe>';
            this.$irContainer.html('<div class="irvidget">' + irCnt + '</div>');
        }
        var rotatedAngle = this.model.get('rotateAngle');
        if (rotatedAngle) {
            this.$el.css({
                '-webkit-transform': 'rotate(' + rotatedAngle + 'deg)',
                '-moz-transform': 'rotate(' + rotatedAngle + 'deg)'
            });
        }





    },
    templates: {
        props: _.template('<label for="name-<%= cid %>">Opacity</label>' +
                '<input type="text" name="opacity" id="opacity-<%= cid %>" value="<%= opacity %>" />' +
                '<div id="file-drop-<%= cid %>"></div>' +
                '<input id="txtServerFileURL-<%= cid %>" class="txtServerFileURL" name="FilePath" type="text" size="60" />' +
                '<label for="name-<%= cid %>">Rotate to</label>' +
                '<input type="text" name="rotateAngle" id="rotate-angle-<%= cid %>" value="<%= rotateAngle %>" />'+
                '<label for="href-<%= cid %>">Hyperlink</label>' +
      '<div id="select-wrapper" style="display:none"  >' +

      '<select id="internalselector" name="href-<%= cid %>">' +
      '<option value="">--</option>'+
      '<% _.each(available_links, function(link) { %>' +
      '<option value="<%= link.href %>" <% if (href == link.href) { %>selected="selected"<% } %>><%= link.title %></option>' +
      '<% }); %>' +
      '</select>' +
      '<%  %>' +
      '</div>' +
                '<input type="button" value="Create IR" class="btn-browse-server" id="btnBrowseServer-<%= cid %>" />' 

                )
    },
    renderProps: function () {
        var available_links = this.model.collection.page.get('available_links');
        return this.templates.props({
            cid: this.cid,
            available_links:available_links,
            loaded: this.model.get('loaded'),
            opacity: this.model.get('opacity'),
            href: this.model.get('href'),
            irlink: this.model.get('irlink'),

            rotateAngle: this.model.get('rotateAngle')
        });
    },

    bindEvents: function (child) {
        if (!child) {
            return;
        }
        WidgetView.prototype.bindEvents.call(this);

        // Fires after image was loaded from users computer.
        this.listenTo(this.model, 'change:loaded', this.completeFileLoad);

        this.listenTo(this.model, 'change:opacity add', this.setOpacity);

        this.listenTo(this.model, 'change:irlink', this.setIr);
        // Initialize file drop tool, after DOM was rendered.
        this.listenTo(this.model, 'after:render:specific:props', this.initFileDrop);
        this.listenTo(this.model, 'after:render:specific:props', this.initBrowseServer);
        this.listenTo(this.model, 'after:render:specific:props', this.initPreview);
        this.listenTo(this.model, 'change:size', this.resizeIr);
        this.listenTo(this.model, 'get:iropenPoPup', this.iropenPoPup);
        this.listenTo(this.model, 'get:irpopupComplete', this.irpopupComplete); 
        this.listenTo(this.model, 'get:irpopupButtons', this.irpopupButtons);
        this.listenTo(this.model, 'get:popupSave', this.popupSave);
        this.listenTo(this.model, 'get:createbrowseButton', this.createbrowseButton);
        this.listenTo(this.model, 'get:irgenerateGuid', this.irgenerateGuid);

        this.listenTo(this.model, 'get:available_links', this.available_links); 



    },
    setIr: function () {
        var link = this.model.get('irlink');
        if (link.match(/<iframe.*.*<\/iframe>/)) {
            this.ir = $(link);
            var size = this.model.get('size');
            this.$el.css('padding', '3px');
            this.ir.attr('width', (size.width - 6) + 'px').attr('height', (size.height - 6) + 'px');
            this.model.set('loaded', true);
            this.$irContainer.html(this.ir);
            // this.model.set('base64Iframe', '');
            this.model.set('filename', '');
            this.model.set('loaded', false);
        }

    },
    resizeIr: function () {
        var widgetSize = this.model.get('size');
        if (this.ir) {
            this.ir.attr('width', (widgetSize.width - 6) + 'px').attr('height', (widgetSize.height - 6) + 'px');
        }
    },
    initFileDrop: function () {

        if (this.$fileDrop) {
            this.$fileDrop[0].ondragleave = null;
            this.$fileDrop[0].ondragover = null;
            this.$fileDrop[0].ondrop = null;
            this.$fileDrop.remove();
        }

        this.$fileDrop = $('#file-drop-' + this.cid);
        var self = this;

        this.$fileDrop[0].ondragleave = function (event) {
            event.stopPropagation();
            event.preventDefault();

            if (!self.model.get('loaded')) {
                self.$fileDrop.removeClass('over');
            }
        };

        this.$fileDrop[0].ondragover = function (event) {
            event.stopPropagation();
            event.preventDefault();

            if (!self.model.get('loaded')) {
                self.$fileDrop.addClass('over');
            }
        };

        this.$fileDrop[0].ondrop = function (event) {
            event.stopPropagation();
            event.preventDefault();

            // Ignore new file if another one already loaded.
            if (self.model.get('loaded'))
                return;

            // Get dropped files.
            var files = event.dataTransfer.files;

            if (files.length) {
                // Get only first file from all given.
                switch (files[0].type.split('/')[0]) {
                    case 'ir':
                    case 'audio':
                        // Save file into the memory.
                        self.file = files[0];
                        self.model.set('loaded', true);
                        self.model.set('irlink', '');
                        self.$irContainer.html('<div class="irvidget">' + self.file.name + '</div>');
                        self.model.set('filename', self.file.name);
                        break;
                }
            }

            self.$fileDrop.removeClass('over');
        };
        this.$rotatorDeg.on('change', function () {
            var deg = this.val();
            console.log("key ")
            this.model.set('rotateAngle', deg);

        });
    },

   IreditorObject.iropenPoPup :  function(clickHandle, contentHandle, width, height) {
       var self = this;
         width = '326';
         height = '400';
       //width = typeof a !== 'undefined' ? a : 600;
      // height = typeof b !== 'undefined' ? b : 300;
        var fancybox_content = '#fancybox-content';
                    $(fancybox_content).css({
                               'position' : 'relative',
                               'display' : 'inline-block',
                               'overlay' : 'hidden'
                            });
       $.fancybox($(contentHandle).html(), {

         autoDimensions: false,
        height: 500,
        width: 600,
        hideOnContentClick: false,




       //  width: width,
       //  height:height,
       // // autoScale: true,
       //  closeClick    : false,
       //  minWidth: 250,
       //  maxWidth: 450,
       //  transitionIn: 'none',
       //  transitionOut: 'none',
       //  hideOnContentClick: false,
       //  modal: true,
       //  closeBtn : true,
        onStart: function () {
              console.log('onStart');
            //On Start callback if needed

        },
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

1 个答案:

答案 0 :(得分:0)

如何在视图中定义全局变量不是Backbone关注的问题,是vanilla JS(https://stackoverflow.com/a/5786899/4327861

 var IrWidgetView = WidgetView.extend({
     IreditorObject: {},
     myVar:window["myGlobalVariable"],
     initialize: function() {

         this.setupMyObject();

     },
     setupMyObject: function() {

         this.IreditorObject.data = {};
         this.IreditorObject.data.imgContainer = [];
         //so on

     }
 });

或者您可以直接添加到视图原型

IrWidgetView.prototype.myVariable = referenceToAGlobalVariable;