Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use global variable in backbone.js view?

Tags:

backbone.js

Is it possible to use global variable in backbone.js view ?

exmpl:

var TodoView = Backbone.View.extend({

 counter: null ; // is this possible ?

 initialize: function(){ 

 this.render();

 },

 render: function(){



}


});
like image 793
Sysrq147 Avatar asked Nov 30 '12 14:11

Sysrq147


People also ask

Can we declare global variable in JavaScript?

Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable. Global Variables are the variables that can be accessed from anywhere in the program.

Can global variables be used anywhere?

You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword.

Is it bad to use global variables in JavaScript?

Avoid globals. Global variables and function names are an incredibly bad idea. The reason is that every JavaScript file included in the page runs in the same scope.

Is using global variables bad in Nodejs?

Global variables are considered an anti-pattern in almost any programming language because they make it very hard to follow and debug code. When you browse the code, you never know which function sets or uses a global variable.


1 Answers

In addition to what Peter already said, if you are interested in having what amounts to a private variable that is available across all instances of the TodoView you create then you could do something like the following.

(function () {
  var counter = 0; //This can be used now as a private variable inside TodoView

  window.TodoView = Backbone.View.extend({

    initialize: function(){ 
      this.render();
      counter += 1;
    },

    render: function(){
    }
  });
})();
like image 170
Andrew Hubbs Avatar answered Oct 20 '22 00:10

Andrew Hubbs