Переменная модели магистрали не определена после инициализации

У меня проблема с неопределенной переменной модели магистрали, хотя я уверен, что в какой-то момент она инициализирована.

AreaOfInterest = Backbone.Model.extend({
    defaults:{
        marker: null, // center of the area
        area: null // area around the center
    },
    initialize: function(){
      console.log("Created new Area of Interest");
    }

})

AreaOfInterestList = Backbone.Collection.extend({
    model: AreaOfInterest,
    initialize: function(){
        console.log("Created new Area of Interest List");
    },
    /*
    Displays all Area Of Interests in the collection
     */
    display: function(){
        console.log("Displaying all Areas of Interest.");
        this.each(function(aoi){
            map.addLayer(aoi.get("marker"));
            map.addLayer(aoi.get("area"));
        })
    },
    /*
     Hides all Area Of Interests in the collection
     */
    hide: function(){
        console.log("Hiding all Areas of Interest.");
        this.each(function(aoi){
            map.removeLayer(aoi.get("marker"));
            map.removeLayer(aoi.get("area"));
        })
    }
});

LocationType = Backbone.Model.extend({

    defaults:{
        id: null,
        name: null,
        type: null,
        areaOfInterestList: new AreaOfInterestList()
    },

    initialize: function(){
    },
    hideAreas: function(){
        console.log("LocationType : Hiding all elements");
        console.log(this.id);
        console.log(this.areaOfInterestList);
        this.areaOfInterestList.hide();
        //FIXME: This is not working yet.
    }
});

var airportType = new LocationType({name: "Airport", type: 'airport', id: 'airport', areaProperties: new AreaProperties({strokeColor: aqua, fillColor: aqua})});
var embassyType = new LocationType({name: "Embassy", type: 'embassy', id: 'embassy', areaProperties: new AreaProperties({strokeColor: teal, fillColor: teal})});


/* In the javascript code, this is ran to show AOIs */
var areaOfInterestList = airportType.get('areaOfInterestList');

console.log("Found " + results.length +  " result!");
for (var i = 0, result; result = results[i]; i++) {
    //Create AOI and adds it to the item.
    var aoi = createAreaOfInterest(result, areaProperties);
    areaOfInterestList.add(aoi);
}
item.set({areaOfInterestList: areaOfInterestList});
var aoil = item.get('areaOfInterestList');
aoil.display();

/* In the javascript code, this is ran to hide AOIs */
airportType.hideAreas();

Итак, в основном мой код состоит из типов местоположений. Каждый тип места (церковь, бар и т. д.) имеет имя и список областей интересов.

И область интереса определяется маркером и областью. Когда пользователь нажимает на флажок, я хочу, чтобы AOI появлялись и исчезали.

У меня проблема в том, что каким-то образом области отображаются, но когда я запускаю метод hideAreas, список считается неопределенным. Кроме того, несмотря на то, что у меня есть несколько типов местоположения, оператор console.log «Создан новый список областей интересов» запускается только один раз.

Вот операторы консоли вместе с ошибкой:

Created new Area of Interest List main.js:58
Selected : train_station main.js:390
Found 21 result! main.js:406
21
Created new Area of Interest main.js:47
Displaying all Areas of Interest. main.js:64
LocationType : Hiding all elements main.js:121
train_station main.js:122
undefined main.js:123
Uncaught TypeError: Cannot read property 'hide' of undefined main.js:124

Я понятия не имею, почему AreaOfInterestList запускается только один раз, даже если он находится по умолчанию в LocationType. Я также не знаю, почему это не определено, когда я пытаюсь его вызвать.

Что я могу упустить?

Вы можете увидеть приложение (с ошибкой) здесь .


person jlengrand    schedule 15.07.2014    source источник


Ответы (1)


Атрибуты модели хранятся в .attributes, но вы почти всегда должны обращаться к ним, используя .get():

hideAreas: function(){
    //...
    console.log(this.attributes.areaOfInterestList);
    this.get('areaOfInterestList').hide();
}

http://backbonejs.org/#Model-attributes

person jgillich    schedule 15.07.2014
comment
Спасибо, это действительно устраняет ошибку. Однако это не решает того факта, что для всех элементов существует только один AreaOfInterestList. У вас есть идея, почему? - person jlengrand; 15.07.2014
comment
Хорошо, если я помещу новый AreaOfInterestList() в инициализацию вместо значения по умолчанию, тогда он будет запускаться каждый раз. Спасибо за помощь! - person jlengrand; 15.07.2014