BackboneJS - this.collection未定义

时间:2013-12-03 17:11:36

标签: json backbone.js

我有这个Backbone View:

define(['backbone','handlebars', 'text!templates/AlphabetList.html'],

    function(Backbone,Handlebars, Template) {


        'use strict';

        var View = Backbone.View.extend({

            template: Handlebars.compile(Template),

            events: {
                'click li':'li_clickHandler'
            },

            li_clickHandler: function(e) {
                var id = $(e.currentTarget).attr('data-id');
                Backbone.history.navigate('/category/'+id, {trigger:true});
            },

            initialize: function () {
            },

            render: function() {
                $(this.el).html(this.template({menu:this.collection.toJSON()}));
                return this;
            }

        });

        return View;

    }
  );

这是我的路由器:

define([
'backbone',
//Views
'views/ArtistTopImage',
'views/AlphabetList',
'collections/AlphabetCollection',
],

function(
    Backbone,
    AlphabetList,
    ArtistTopImage,
    AlphabetCollection
    ) {

    'use strict';

    var ArtistRouter = Backbone.Router.extend({

        routes: {
            '': 'index'
        },

        //Initializing the application
        initialize: function () {
            var self = this;

            //Collections
            this.AlphabetCollection = new AlphabetCollection({catId:0});

            //Views
            this.artistTopImageView = new ArtistTopImage({el:'.ti'});
            this.AlphabetList = new AlphabetList({el:'#alphabetical', collection:this.AlphabetCollection});

            self.artistTopImageView.render();

            this.AlphabetCollection.fetch({success: function(collection) {
                self.AlphabetList.collection=collection;
                self.AlphabetList.render();
            }});

            Backbone.history.start({
                pushState: false
            });
        },

        //Default route.
        index: function () {
            var self = this;

        },

    });

    return ArtistRouter;
}
    );

这是我的收藏:

define([
 "backbone",
 "models/AlphabetModel"
],

 function(Backbone, AlphabetModel) {
var AlphabetCollection = Backbone.Collection.extend({
    model: AlphabetModel,

    catId: null,

    initialize: function(attrs) {
        this.catId=attrs.catId;
    },

    url: function() {
        return "Alphabetical"+this.catId+".json";
    }
});

return AlphabetCollection;
    });

HTML模板

<ol class="alist">
{{#each menu}}
<li data-id="{{this.url}}">{{this.name}}</li>
{{/each}}
</ol>

和JSON文件:

[
{
    "name":"0-9",
    "id":"1",
    "url":"0"
},
{
    "name":"A",
    "id":"2",
    "url":"1"
},
{
    "name":"B",
    "id":"3",
    "url":"2"
},
{
    "name":"C",
    "id":"4",
    "url":"3"
},
{
    "name":"D",
    "id":"5",
    "url":"4"
}
   ]

这给了我一个错误:“this.collection未定义”。我不知道问题是什么,有人有想法吗?

0 个答案:

没有答案