Backbone收集的fetch方法没有调用?

时间:2014-06-16 07:02:03

标签: backbone.js backbone-views backbone-events backbone-collections

我正在使用yoeman脚手架来创建和构建Backbone项目。我正在尝试下面的代码无法在视图的初始化块中获取集合的数据。我在控制台中没有收到任何错误。我试图调试,但它没有成功阻止。你有没有人告诉我在Backbone View中使用收集的正确方法。

contacts.json

[
    {
        "id": 1,
        "name": "first name",
        "mobile": "xxx-xxx-xxxx",
        "email": "anshuls@abc.com"
          },
    {
        "id": 2,
        "name": "second name",
        "mobile": "xxx-xxx-xxxx",
        "email": "anshuls@abc.com"
          }
     ]

//模型

define([
    'underscore',
    'backbone'
], function (_, Backbone) {
    'use strict';

    var ContactModel = Backbone.Model.extend({      
        initialize: function() {

        },

        defaults: {
            name:null,            
            mobile:null,
            email:null,
            avatar:null
        }    

    });

    return ContactModel;
});

//收集

    define([
        'underscore',
        'backbone',
        'models/contact'], function (_, Backbone, ContactModel) {
        'use strict';

        var ContactCollection = Backbone.Collection.extend({
            model: ContactModel,
            url: 'scripts/json/contacts.json',
            initialize: function () {
            }       
        });

        return ContactCollection;
    });

//视图

    define([
    'jquery',
    'underscore',
    'backbone',
    'templates',
    '../views/contact',
     '../collections/contact'
], function ($, _, Backbone, JST, ContactView, ContactCollection) {
    'use strict';

    var ContactsView = Backbone.View.extend({
        template: JST['app/scripts/templates/contacts.hbs'],          
        initialize: function () {
            var self = this;
            this.collection = new ContactCollection();
            this.collection.fetch({
                success: function (collection,response) {
                    console.log('Collection fetch success' + response);
                    console.log('Collection models: ' + collection.models);

                }
            });
        }
    })
    return ContactsView;
});

2 个答案:

答案 0 :(得分:0)

尝试向collection.fetch添加错误块,并查看是否正在调用错误块:

this.collection.fetch({
                success: function (collection,response) {
                    console.log('Collection fetch success' + response);
                    console.log('Collection models: ' + collection.models);

                },
                error: function(model, xhr, options) {
                    console.log('error'); <-- debug here
                }
            });

答案 1 :(得分:0)

集合是否实际发出数据请求?你在网络标签中看到它吗?