在主干视图中定义变量的最佳实践

Best practice for defining variables in a Backbone view

本文关键字:最佳 变量 定义 视图      更新时间:2023-09-26

我有一个主干视图,必须处理大量的逻辑。我正在使用require.js,我想知道创建变量的最佳方式是什么。我当前的设置是这样的。

define([
'jquery',
'underscore',
'backbone',
'pixi',
'tweenlite',
'easepack',
'app/models/tower-item-model',
'app/views/tower-item-view',
'app/templates'
], function($, _, Backbone, PIXI, TweenLite, EasePack, TowerItemModel, TowerItemView, Templates){
'use strict';
// ********* create view variables ************
var numberOfTowers = 1;  // this is set by the icons in the top right of the view. Default is 1
var sectionWidth = 180;
var mmToPixelRatio = 180/300;
var currentWidth = 0;
var currentHeight = 0;
var currentDepth = 0;
var frameColourPressed = false;
var hiliteIntensity = 0;
var hiliteUp = true;
var hiliteIntervalID;

var TowerView = Backbone.View.extend({
    id: 'tower-view',
    className: 'tower-view',

我认为这些变量当前在全局命名空间中是正确的吗?如果是这样的话,我想这并不好。我这样设置了另一个视图应用程序创建了它的几个实例。我注意到一个变量对一个实例的改变会影响到所有的变量。

是否有一种更简单的方法来声明变量,使它们成为真正的实例变量?

多谢

您可以简单地在视图类中添加变量

例如,

var TowerView = Backbone.View.extend(
{
    id: 'tower-view',
    className: 'tower-view',
    currentWidth : 0,
    currentHeight : 0,
    currentDepth : 0,
    frameColourPressed : false,
    setTowerHeight : function()
                     {
                         console.log(this.currentwidth);
                     }
});

这些被称为真正的类变量,它们在每个实例中是不同的。