javascript - Backbone : Cannot call method 'bind' of undefined

标签 javascript jquery backbone.js

我目前正在通过截屏教程学习 backbone.js,在学习过程中,我的代码似乎停止工作,在 Chrome 的 javascript 控制台中抛出错误 Cannot call method 'bind' of undefined。错误行包含在 initialize 函数中:

window.PlaylistView = Backbone.View.extend({
    tag: 'section',
    className: 'playlist',

    initialize: function() {
        _.bindAll(this, 'render');
        this.template = _.template($('#playlist-template').html());
        this.collection.bind('reset', this.render);  //<<<<<< THIS LINE

        this.player = this.options.player;
        this.library = this.options.library;
    },

    render: function() {
        $(this.el).html(this.template(this.player.toJSON()));

        this.$('button.play').toggle(this.player.isStopped());
        this.$('button.pause').toggle(this.player.isPlaying());

        return this;
    }
});

我不知道this.collection是什么意思,为什么 View 有一个集合,不是模型的集合?在其他 View 中使用的 this.collection.bind() 似乎没有抛出任何错误。在调用 this.collection.trigger('select', this.model); 并扩展 window.AlbumViewwindow.LibraryAlbumView 中,我不查看 window.AlbumView 中任意位置定义的任何集合,但不会抛出任何错误。这似乎让我感到困惑。

JSFIDDLE

编辑:

错误已修复,因为不是

window.Player = Backbone.Model.extend({
        defaults: {
            'currentAlbumIndex': 0,
            'currentTrackIndex': 0,
            'state': 'stop'
        },

        initialize: function() {
            this.playlist = new Playlist();
        },

我有

window.Player = Backbone.Model.extend({
        defaults: {
            'currentAlbumIndex': 0,
            'currentTrackIndex': 0,
            'state': 'stop'
        },

        initialize: function() {
            playlist = new Playlist();    // <<< this line changed!
        },

还有之前的this.collection指的是这里的集合,

window.BackboneTunes = Backbone.Router.extend({
    routes: {
        '': 'home',
        'blank': 'blank'
    },

    initialize: function() {
        this.playlistView = new PlaylistView({
            collection: window.player.playlist,  // <<<< THIS ONE!
            player: window.player,
            library: window.library
        });

        this.libraryView = new LibraryView({
            collection: window.library
        });
    },

最佳答案

主干 View 包含一个集合或一个模型,因为 View 用于呈现模型或模型集合中包含的数据。

这个例子会抛出一个错误,因为 this.collection 还没有被定义。为此,您需要初始化一些集合,然后将其传递给您的 View 。

new PlayListView({collection: someCollection});

关于javascript - Backbone : Cannot call method 'bind' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10995413/

相关文章:

javascript - 在不重新加载页面的情况下修改查询字符串

javascript - Outlook Web 插件显示错误消息作为信息

javascript - 执行。 func只要按住鼠标左键(纯js)

javascript - Firebase Web Push 后台消息永远不会显示

javascript - 延迟 href 执行点击,直到 ajax 调用之后

jquery - Css 图像叠加通过 Bootstrap 做出响应

javascript - 如何使用 Rails 从数字字段执行 jQuery ajax 调用

jquery - 使用 JQuery UI 将单选按钮转换为 slider 元素

javascript - Backbone.js 使用 native websockets 同步

javascript - 如何从 Backbone 路由器中提取 id 参数