骨干101 - 将JSON数据与骨干一起使用

时间:2013-03-15 18:31:06

标签: javascript json backbone.js

我正处于将应用程序迁移到骨干框架的开始阶段。

我有一些来自ajax调用的json数据

{f1:"f1_value", f2:"f2_value", f3:"f3_value"},
{f1:"f1_value", f2:"f2_value", f3:"f3_value"},
{f1:"f1_value", f2:"f2_value", f3:"f3_value"},

此数据集总是有3列,但就行而言,可能只要每组所需的时间长。

它用于在将客户端处理成HTML之后填充div,相关地可以根据需要向下扩展。我正在计划这个数据块表示框架中的一个视图。

<div id = "data_hold"></div>

我如何将其与框架相匹配:

    var ModelTest,
        CollectionTest,
        ViewTest;

    ModelTest = Backbone.Model.extend({
    });
    CollectionTest = Backbone.Collection.extend({
        model: ModelTest
    }
    ViewTest = Backbone.View.extend({
    });

1 个答案:

答案 0 :(得分:2)

Backbone 101:

var ModelTest,
    CollectionTest,
    ViewTest;

ModelTest = Backbone.Model.extend({ });

// associate your collection with a URL.  This is static here; it can be
// passed in as an option using the Collection's initialize function()
// instead.

CollectionTest = Backbone.Collection.extend({
    model: ModelTest,
    url: 'http://localhost/my_json_source'
});

ViewTest = Backbone.View.extend({
    // Have a target to render into.  This can be an existing element, as  
    // here, or it can be dynamically generated and attached to the DOM
    // programattically.
    el: $('#data_hold'),

    // specify than when the collection is updated, call the local render
    // method.

    initialize: function(options) { 
        this.collection.bind('reset', _.bind(this.render, this));
    },

    // Empty the element, then append subsequent rows of the collection
    // to it as paragraphs.  The '_this = this' idiom allows us to access
    // the outside context (the View's context), since the each() call 
    // will create a new inner context.

    render: function() {
        var _this = this;
        this.$el.html('');
        this.collection.each(function(l) {
            _this.$el.append('<p>' + l.get('f2') + '</p>');
            });
    }
});

// initialize the collection and view, then fetch the collection, which
// will trigger the render after the collection has been updated.

$(function() {
    ct = new CollectionTest();
    vt = new ViewTest({collection: ct});
    ct.fetch();
});
相关问题