关于Backbone.js:RequireJS BackboneJS-连接模块

RequireJS + BackboneJS - connect modules

当我尝试连接包含BackboneJS的两个不同视图的两个模块时遇到问题。

在RequireJS的此模块中包含主干视图。
我需要在此模块中,引用另一个模块中的主干视图。
我修改了代码以使其更简单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
define (["jquery","backbone","collections/controlSearchCollection","views/currentPlaylist","jqueryUI"], function($, Backbone, controlSearchMusic, currentPlaylist){

var searchModule = Backbone.View.extend({
    el:"#containerSearch",

    initialize: function () {
        this.collection = new controlSearchMusic();
    },
    events:{
       "dblclick li":"select"
    },
    select: function(element){
        var trackJSON ={};
        trackJSON["id"]="playCloud_"+$(element.target).attr("id");
        currentPlaylist.collection.add(trackJSON);   <--- Here is where this error

    }
});

return searchModule;
});

在这里,我的RequireJS的另一个模块包含了ribsJS的视图。我需要从第一个模块添加到JSON。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
define (["jquery","backbone","collections/controlCurrentPlaylistCollection","jqueryUI"], function($, Backbone, controlCurrentPlaylist){

    var currentPlaylist = Backbone.View.extend({
        el:"#currentPlaylist",

        initialize: function(){
            this.collection = new controlCurrentPlaylist();
            this.collection.on("add", this.executeFunction, this);

        },
        executeFunction: function(song){
            alert(song.toSource());
        }
    });
    return currentPlaylist;
});

这两个模块在app.js中实例化

有人可以帮助我吗?谢谢!


没有确切的错误很难说,但是看起来您还没有创建currentPlaylist的实例。因此,currentPlaylist.collection是未定义的,并且当您尝试在其上调用add函数时会导致错误。

您可以尝试以下操作:

1
2
var cpl = new currentPlaylist(); // create instance
cpl.collection.add(trackJSON);  // cpl.collection should be initialized here