BackboneJs fetch()Json在View上显示

时间:2014-11-18 09:31:14

标签: json backbone.js

我正在尝试使用backbonejs来获取()从服务器发送的JSON数据,以便在视图中显示它。但它没有用。

这是我的主干

$(function () {


var Service = Backbone.Model.extend({
    url: "/api/album/1",
    defaults: {
        id: '1',
        title: 'abc',
        article: 'abc'

    },
    parse: function (response) {
        return response.data;
    }
});


// Create a collection of services
var ServiceList = Backbone.Collection.extend({
    // Will hold objects of the Service model
    url: "/api/album/1",
    model: Service

});

var ServiceView = Backbone.View.extend({
    tagName: 'li',
    events: {
        'click': 'toggleService'
    },
    initialize: function () {

        this.listenTo(this.model, 'change', this.render);
    },
    render: function () {

        this.$el.html('<input type="checkbox" value="1" name="' + this.model.get('title') + '" /> ' + this.model.get('title') + '<span>$' + this.model.get('artist') + '</span>');
        this.$('input').prop('checked', this.model.get('checked'));

        return this;
    },
    toggleService: function () {
        this.model.toggle();
    }
});

var App = Backbone.View.extend({

    model: Service,
    el: $('#main'),
    initialize: function () {
       this.model = new ServiceList();
        this.model.fetch();


        this.list = $('#services');

       this.model.each(function (service) {

            var view = new ServiceView({model: service});
            this.list.append(view.render().el);

        }, this);
    },
    render: function () {

        return this;

    }

});

new App();
});

这是我的JSON

  

{&#34;数据&#34; {&#34; ID&#34;:&#34; 1&#34;&#34;艺术家&#34;:&#34;高堤耶&#34 ;, &#34;标题&#34;:&#34;制作镜子&#34;}}

请忽略我在backbonejs中的错误命名约定,我试图让它工作

1 个答案:

答案 0 :(得分:2)

试试这个

var App = Backbone.View.extend({
  el: $('#main'),

  initialize: function() {
    var serviceList = new ServiceList(),
      // if you don't have #services in html
      //services    = $(this.el).html('<div id="services"></div>'),
      services = $(this.el).find('#services'),
      serviceView;

    serviceList.fetch({
      success: function(collection) {
        collection.each(function(model) {
          serviceView = new ServiceView({
            model: model
          });

          services.append(serviceView.render().el);
        });
      }
    });
  },

  render: function() {
    return this;
  }
});

DEMO:http://jsbin.com/hiziqi/1/在此演示中,我将url更改为远程服务器