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(){
}
});
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.
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.
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.
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.
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(){
}
});
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With