为什么我的模型中的默认属性返回未定义

Why are the default attributes in my model returning undefined

本文关键字:属性 返回 未定义 默认 我的 模型 为什么      更新时间:2023-09-26

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

   JAWeatherWatch.module('Cities', function(Cities, JAWeatherWatch, Backbone, Marionette){       /*城市        * 此模型用于对开放天气 API 引用的数据进行建模        * 牙买加每个城市        */       Cities.City = Backbone.Model.extend({            默认值:{                存储我的 API 密钥以及要添加到请求中的所需查询字符串                apiKey: '&APPID=84cb7efaf4ac2947aa6381637904ee5e',                国家:"牙买加",                教区名称:假            },            url:'http://api.openweathermap.org/data/2.5/weather?q=' + this.parishName + "," + this.country + this.apiKey,            初始化: 函数(){                console.log(this.country);=> "未定义"                待办事项:从 API 获取 JSON 数据            }        });});var test = new JAWeatherWatch.Cities.City({parishName:'kingston'});    console.log(test.get('country'))//=> 'Jamaica'

奇怪的是,在模型实例化后,它们的行为符合预期(即返回正确的值)。我完全不知道为什么会这样

> 你不能使用 this.country ,因为 backbone 将模型的属性存储在模型中一个名为 attributes 的键中。因此,理论上可以使用this.attributes.country访问它们。但请不要那样做。应使用以下model.get()访问模型属性

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

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