【问题标题】:TypeError: Cannot call method 'bind' of undefined error in Backbone with Django-TastypieTypeError:无法使用 Django-Tastypie 在 Backbone 中调用未定义错误的方法“绑定”
【发布时间】:2013-10-17 20:50:05
【问题描述】:

我正在写一个简单的例子来学习 Backbone 和 Django-Tastypie。我正在使用 Backbone.js 1.0。

在控制台中,当我尝试notes = new NoteListView(); 时,我收到错误TypeError: Cannot call method 'bind' of undefined

根据我在网上阅读的内容,我认为这是因为模板没有实例化。但是,模板缓存在视图上的模板调用中。所以,我很困惑。

也许我的想法完全错误,但应该发生的是绑定发生在已缓存的模板上,以便它可以执行设置并填充模板。

TastpieCollection 和 TasttypieModel 来自 http://paltman.com/2012/04/30/integration-backbonejs-tastypie/,这似乎工作得很好。

$(function() {

    // Note: The model and collection are extended from TastypieModel and TastypieCollection
    // to handle the parsing and URLs

    window.Note = TastypieModel.extend({});

    window.Notes = TastypieCollection.extend({
        model: Note,
        url: NOTES_API_URL
    });

    window.NoteView = Backbone.View.extend({

        template: _.template($('#notes-item').html()),

        initialize: function () {
            _.bindAll(this, 'render');
            this.model.bind('set', this.render);
        },
        render: function() {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }
    })

    window.NoteListView = Backbone.View.extend({

        template: _.template($('#notes-item-list').html()),

        initialize: function () {
            _.bindAll(this, 'render');
            this.collection.bind('set', this.render);
        },
        render: function() {
            var $notes,
                collection = this.collection;
            this.$el.html(this.template());
            $notes = this.$('.notes');
            collection.each(function(note){
                var view = new NoteView({
                    model: note,
                    collection: collection
                });
                $notes.append(view.render().el);
            });
            return this;
        }
    })
})

那么,两个问题:

问题一:错误内容是什么,我该如何解决?

问题二:setreset 使用方式的新版本……对吗?

感谢您的帮助。

【问题讨论】:

  • model: Note 应该是 model: note。没有'set'事件,有'add''remove''change'事件。
  • 我做了两处修改,Note to note 和 notes.append 放错了地方。两者都固定。
  • 我对没有设置的事件感到困惑。我在这里从backbone.js 的文档中得到这个:backbonejs.org/#Collection-set
  • Collection#set 文档说“所有适当的'add''remove''change' 事件都会在这种情况发生时被触发”,这是因为set 就是这样做的,它只是找出需要添加、删除和更改的组合。

标签: django backbone.js underscore.js backbone-views tastypie


【解决方案1】:

您没有设置集合,这是您的错误消息的原因。您应该执行以下操作来修复该特定错误消息:

notes = new NoteListView({collection : new Notes()});

【讨论】:

  • 我会在哪里做呢?在视图中初始化?在 view.render 中?
  • 我想通了。我要么需要在初始化函数中使用它,要么在控制台中手动添加。以后我会通过路由器添加。
猜你喜欢
  • 2012-11-12
  • 2014-09-18
  • 1970-01-01
  • 2014-03-21
  • 2015-01-21
  • 2014-09-18
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多