为什么我的模型中的默认属性返回undefined

时间:2015-01-16 07:58:22

标签: javascript backbone.js marionette

我已经定义了我的模型及其默认变量;然而,每当我尝试在模型本身内使用任何这些变量时,它们的值都设置为“未定义”。


    JAWeatherWatch.module('Cities', function(Cities, JAWeatherWatch, Backbone, Marionette){

        /*  Cities
        *   This model is used to model the datat retued by the open weather api 
        *   for each individual city in jamaica
        */
        Cities.City = Backbone.Model.extend({
            defaults:{
                // stores my api key as well the required query string to add to the request
                apiKey: '&APPID=84cb7efaf4ac2947aa6381637904ee5e',
                country:'jamaica',
                parishName: false
            }, 
            url:'http://api.openweathermap.org/data/2.5/weather?q=' + this.parishName  + "," + this.country + this.apiKey,
            initialize: function(){

                console.log(this.country); // => 'undefined'

                // todo: get json data from api
            }
        });


    });


    var test = new JAWeatherWatch.Cities.City({parishName:'kingston'});
    console.log(test.get('country')) // => 'jamaica'

奇怪的是,在实例化模型后,它们的行为与预期一致(即返回正确的值)。我完全不知道为什么会出现这种情况

1 个答案:

答案 0 :(得分:2)

您无法使用this.country,因为骨干将模型的属性存储在模型中名为attributes的密钥中。所以可以使用this.attributes.country在理论上访问它们。但请不要这样做。应使用model.get()

访问模型属性

所以在你的情况下,this.get( "country" )

如果您想了解更多信息,请参阅Backbone文档。 http://backbonejs.org/#Model-get