骨干js和填充使用获取的数据模型() [英] Backbone js and populating a model with data using fetch()

查看:173
本文介绍了骨干js和填充使用获取的数据模型()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作骨干JS和我试图填充使用数据提取模型。问题是,提取似乎是工作,但我的模型不填充数据。

I'm working in Backbone js and I am trying to populate a model with data using fetch. The problem is that the fetch appears to be working but my model is not populating with data.

的code代码片段:

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作为回报看起来是这样的:

And the JSON being return from the server looks like this:

{"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":"'"}

警报总是不确定的。我失去了一些东西?

The alert is always undefined. Am I missing something?

推荐答案

取是异步,这就是为什么它有成功错误回调。所以这是没有确定的数据是由您尝试获取属性的时间获取。 试试这个:

Fetch is async, that's why it has success and error callbacks. So it's no sure that the data are fetched by the time you try to get the property. Try this:

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

这篇关于骨干js和填充使用获取的数据模型()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆