virushree virushree - 4 months ago 5x
JSON Question

want to access variable from function to render function in backbone

getGeoLevelDetails: function(id) {
window.gid = id;

I want to access

renderGeoLevelDetails: function(response, obj){
var id = this.getGeoLevelDetails.gid;

It isshowing me output as

Uncaught TypeError: Cannot read property 'gid' of undefined


There are a few errors in your approach.

First you are defining a global variable assigned to the DOM window object, this inside a function which i don't really know where it's declared. But this is not really important at this phase.

Second you want to obtain the value assigned to the global variable by calling the above function, which does not return anything.

You have a few options here: either assign the value to the global variable (which is a very bad practice, this should be avoided in any case).

The better approach would be to simply return id:

getGeoLevelDetails: function(id) {
     return id;

Later you can obtain this id by calling in the renderGeoLevelDetails function.

renderGeoLevelDetails: function(response, obj) {
     var id = this.getGeoLevelDetails();

Please note this is working only if you are calling the this.getGeoLevelDetails function from the same scope, because this is an instance of the same object.

There is another big error in your code regarding this line:


First your are not invoking as a function but as an instance variable, expecting to return a globally declared object. This is the reason you are getting:

Uncaught TypeError: Cannot read property 'gid' of undefined


To sum up, if you wish to transfer a value from a model to a view you can access this by calling the model inside the view, or if you wish to obtain a value inside the same view you can use the approach presented above.

If none of the above solutions are fitted for your needs there is another method you can approach: to extend the Backbone object, then declare an object variable which receive the desired value. This way you will eliminate the global pollution issue:


Backbone.Details = _.extend({}, Backbone.Router);   
Backbone.Details.geoLevel = id;

This variable: Backbone.Details.geoLevel then will be accessible from anywhere in your application.