【问题标题】:Backbone js and populating a model with data using fetch()Backbone js 并使用 fetch() 使用数据填充模型
【发布时间】:2012-05-26 18:03:14
【问题描述】:

我正在使用 Backbone js,我正在尝试使用 fetch 使用数据填充模型。问题是提取似乎正在工作,但我的模型没有填充数据。

一个sn-p的代码:

Backbone.emulateHTTP = true;
    Backbone.emulateJSON = true;

    ComponentsModel = Backbone.Model.extend({

        initialize : function() {

        },
        defaults : {
            component_id : null
        },
        urlRoot : "/components/ajax_component",

    });

    ComponentsView = Backbone.View.extend({
        el : $('body'),

        events : {
            'change #component-selector' : 'changeComponent',
        },

        initialize : function() {
            _.bindAll(this, 'render', 'changeComponent');
            this.render();
        },

        changeComponent : function(e) {
            var clickedEl = $(e.currentTarget);
            var value = clickedEl.attr("value");
            var component = new ComponentsModel({id :value, component_id :value });
            component.fetch();
            component.toJSON();
            alert(component.get('component_name'));

        },

        render : function() {

        },
    });

从服务器返回的 JSON 如下所示:

{"component_id":"1","component_name":"Test Component 1","component_description":"A simple test component","component_required":"","user_id":"1","component_approved":"0","component_price":"0","component_overview":"'"}

警报始终未定义。我错过了什么吗?

【问题讨论】:

    标签: javascript jquery ajax backbone.js


    【解决方案1】:

    Fetch 是异步的,这就是它有 successerror 回调的原因。因此,不确定在您尝试获取该属性时是否已获取数据。 试试这个:

    component.fetch({
       success: function(){
           // Now you got your data
       }});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 2014-12-13
      • 1970-01-01
      • 2015-11-05
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多