1

这里有一个小提琴

包含一个模型

Item = Backbone.Model.extend({....})
Apvdtl = Backbone.Model.extend()

和一个集合

Apvdtls = Backbone.Collection.extend({
    model: Apvdtl
})

并使用 Apvdtl 模型填充集合,例如

apvdtls.add([{ itemid: 'c4676cef679a11e28b7a3085a942bd8e', qty: 10 }, 
             { itemid: '1da17339690f11e285d63085a942bd8e', qty: 5 }])

并生成了这个视图

网格1

但我想做的是做出这样的看法

网格2

通过在此JSON 文件上获取带有 ID 的项目

ApvdtlView = Backbone.View.extend({
    tagName: 'tr'
    initialize: function(){
        this.model.on('change', this.render, this);
        this.template = _.template('<td><%=itemid%></td><td><%=qty%></td>');
    },
    render: function(){

        item.set({'id': this.model.get('itemid')});
        // item = {id: 'c4676cef679a11e28b7a3085a942bd8e'}

        item.fetch(); // but this doesnt get the data
        // this should contain this data after i fetch 
        // item = {"id": "c4676cef679a11e28b7a3085a942bd8e",
        //         "code": "prp125", "descriptor": "Paper", "price": "7.00"}

        // build new data to render
        var data = {
            "itemid": item.get('descriptor'),
            "qty": this.model.get('qty')
        }

        this.$el.html(this.template(data));
        //this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});
4

1 回答 1

1

第一个Ajax 是 Async。因此,您永远不知道响应何时返回,因此最好将其附加到事件中。

ApvdtlView = Backbone.View.extend({
    tagName: 'tr',
    initialize: function () {

            // This listens to the sync and change event and renders the item
        this.listenTo(this.model, 'change sync', this.render);
        this.template = _.template('<td> <%=itemid%> </td>' +
            '<td><%=qty%></td>');
        this.model.fetch();

    },
    render: function () {

        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

url必须为模型设置下一个属性,ApvdtlView因为它是从服务器获取的。

接下来是您无法从您的域中点击此网址

urlRoot: 'https://raw.github.com/jrsalunga/prism2/master/www/api/item.json'

因为它是一个不同的域,因为它违反了跨源策略。你需要用来jsonp得到这个

检查小提琴

JSONP 请求小提琴

现在您可以看到在网络选项卡中获取的数据,但由于必须在服务器端处理回调而引发错误

于 2013-07-23T09:19:50.773 回答