我已经定义了我的模型及其默认变量;然而,每当我尝试在模型本身内部使用这些变量中的任何一个时,它们的值都会设置为“未定义”。
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'
奇怪的是,在实例化模型后,它们的行为符合预期(即返回正确的值)。我完全不知道为什么会这样
最佳答案
您不能使用 this.country
,因为主干将模型的属性存储在模型内名为 attributes
的键中。因此理论上可以使用 this.attributes.country 访问它们。但请不要这样做。应使用 model.get()
所以在你的情况下,这将是 this.get( "country")
如果您想了解更多信息,请参阅 Backbone 文档。 http://backbonejs.org/#Model-get
关于javascript - 为什么我的模型中的默认属性返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27979474/