Sysrq147
Sysrq147

Reputation: 1367

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

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(){



}


});

Upvotes: 10

Views: 21798

Answers (3)

Peter Lyons
Peter Lyons

Reputation: 146054

You can easily store variables in at least 3 different scopes:

  • Regular instance variables unique to each view instance
    • these can be stored as properties on the view's this object
    • Example: this.selectedItem = this.$el.find('.selected');
  • Class-level variables shared by all instances of the view
    • these can be stored on the View class's constructor function
    • Example: TodoView.counter = 0; (put that after your entire .extend invocation)
  • True global variables (yes, these are bad, but since you asked)
    • you can leak these by omitting var or just explicitly assign to the window object
    • Example: window.appLaunchTime = new Date()

Upvotes: 23

prince
prince

Reputation: 1

try putting it in static scope

var TodoView = Backbone.View.extend({
TodoView.counter++//reference it this way
},{
 counter: null ;})

may serve somewhat like a global variable

Upvotes: 0

Andrew Hubbs
Andrew Hubbs

Reputation: 9426

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(){
    }
  });
})();

Upvotes: 4

Related Questions