2016-07-20 101 views
1

我是新的阅读骨干js和我有一些严重的问题与通过论据骨干js。骨干js传递论据

var Song = Backbone.Model.extend(); 
var Songs = Backbone.Collection.extend({ 
    model: Song 
}); 
var SongView = Backbone.View.extend({ 
    el: "li", 
    render: function() { 
    this.$el.html(this.model.get("title")); 
    return this; 
    } 
}); 
var SongsView = Backbone.View.extend({ 
    el: "ul", 
    initialize: function() { 
    this.model.on("add", this.onSongAdded, this); 
    }, 
    onSongAdded: function(song) { // when object is added to a collection add event is triggerd 
    // the handler for this event get an argument which is the object that was just added 
    //in this case it refers to a song model so we simply pass it to our songView which is responsible for rendering a song an then we use jquery append method 
    // to append it to our list 
    var songView = new SongView({ 
     model: Song 
    }); 
    this.$el.append(songView.render().$el); 

    }, 
    render: function() { 
    var self = this; 
    this.model.each(function(song) { // 
     var songView = new SongView({ 
     model: Song 
     }); 
     self.$el.append(songView.render().$el); 
    }); 
    } 
}); 
var songs = new Songs([ 
    new Song({ 
    title: "1" 
    }), 
    new Song({ 
    title: "2" 
    }), 
    new Song({ 
    title: "3" 
    }) 
]); 
var song_1 = new Song({ 
    title: "hello" 
}); 
var songsView = new SongsView({ 
    el: "#songs", 
    model: Songs 
}); 
songsView.render(); 

,你可以看到我有这样的功能:onSongAdded 我们有一些内置活动,如补充说,获得3个参数是这样的: 插件(收集,模型,期权) 我怎么能在我的代码中使用这些参数? 你能帮助我吗?

回答

0

el选项用于将视图指向DOM中已存在的元素。您的项目视图应该创建新的<li>元素,因此您应该使用tagName选项。

在您的集合视图构造函数中,您定义了el选项,并且在实例化它时传递了另一个el选项。如果#songs是DOM中的<uL>,那么在构造函数中定义el: "ul",时没有用处。

此外,不需要手动实例化模型,只需将对象传递到集合中,集合将在内部执行。并且不通过收集model,将其作为collection传递。

+0

非常感谢亲爱的! –