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

标签 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'

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

最佳答案

您不能使用 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/

相关文章:

javascript - 向参数对象添加值

javascript - Backbone.Marionette 扩展区域阻止 onClose() 函数调用

backbone.js - 如何在 mustache 上使用Backbone.Marionette.ItemView

javascript - 幻灯片按钮下划线和淡出动画

javascript - 使用 AngularJS 在同一表行中重复一组 <td>

javascript - 在集合中创建新实例后,不要在端点(主干)上执行 GET 请求

javascript - Backbone : Trigger not working properly

javascript - Google map JS API "StreetViewPanorama"某些地址显示黑屏

javascript - 访问组件内的函数?

javascript - 使用 Backbone js 读取 XML 并附加到 View 中