object is possibly undefined error when trying to declare a variable in backbone model

118 Views Asked by At

I am using a backbone model:

export class test = Backbone.Model.extend({
     defaults: {
     name : ''},
     x = 'test'
)}{

function(){
console.log(this.x)}
}

However I get an error on the console. log that says 'property x may not exist on type test'. Am I declaring global variables wrong in backbone? Im quite new to js

1

There are 1 best solutions below

0
harmancode On

To access x defined in the Backbone Model/View and access it from somewhere else, you can define it as an attribute like so: x: null or give any value. By the way, defining it is not mandatory.

var TestModel = Backbone.Model.extend({
    defaults: {
        name: '',
        x: 0,
    },
});

var myTestModel = new TestModel();

console.log(myTestModel.x);

This would print zero.

You can do the same with a view.

Does this answer your question?