【问题标题】:Why are the default attributes in my model returning undefined为什么我的模型中的默认属性返回未定义
【发布时间】:2015-03-14 19:02:05
【问题描述】:

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

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); // => '未定义' // todo: 从 api 获取 json 数据 } }); }); var test = new JAWeatherWatch.Cities.City({parishName:'kingston'}); console.log(test.get('country')) // => 'jamaica'

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

【问题讨论】:

  • 是的,因为this.country 真的是未定义的使用this.get('country')
  • 我试过了,得到以下错误:'TypeError: this.get is not a function'

标签: javascript backbone.js marionette


【解决方案1】:

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

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

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

【讨论】:

  • 解决了这个问题。在单独的函数中使用 this.get 连接字符串。
猜你喜欢
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
相关资源
最近更新 更多