Backbone + RequireJS:Collection.each()不起作用

时间:2012-08-27 06:10:51

标签: javascript backbone.js requirejs

我正在尝试在RequireJS之上实现一个简单的Backbone应用程序,但事情并没有成功。具体来说,我不能让Collection迭代自己。以下是从各自文件中提取的模型/集合/视图。

型号:

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

    var m_Song = Backbone.Model.extend({
    });

    return m_Song;
});

收集:

define([
    'backbone',
    '../models/model'
], function(Backbone, m_Song) {
    'use strict';

    var c_Songs = Backbone.Collection.extend({
        model: m_Song,

        url: './path/to/JSON.json',

        initialize: function() {
            this.fetch();
        }
    });

    return new c_Songs();
});

查看:

define([
    'jquery',
    'underscore',
    'backbone',
    '../collections/collection'
], function($, _, Backbone, c_Songs) {
    'use strict';

    var v_Main = Backbone.View.extend({
        initialize: function() {
            this.render();
        },

        render: function() {
            var $_html = (function(){
                var $_res = [];

                console.log(c_Songs);

                c_Songs.each(function($_v, $_k) {
/* =====================> Codes in here won't run <===================== */
                });

                _.each(c_Songs, function($_v, $_k) {
/* =====================> Won't run either <===================== */
                });

                return $_res;
            })();

            return this.$('tbody').append($_html);
        }
    });

我做错了吗?对于记录,以下是console.log(c_Songs);

的输出
─ d
  ├─ _byCid
  ├─ _byId
  ├─ length
  └─ models
     ├─ length
     └─ 0
        ├─ _callbacks
        ├─ _escapedAttributes
        ├─ _pending
        ├─ _previousAttributes
        ├─ _silent
        ├─ attributes
           └─ (My JSON response can be found here!)
        ├─ changed
        ├─ cid
        └─ collection

但我确信我不应该像c_Songs.models[0].attributes这样奇怪的方式访问我的JSON数据;一定有什么不对劲。

我该如何正确地让Collection迭代自己?

1 个答案:

答案 0 :(得分:1)

感谢mu!

找到了完美的解决方案here