我的超级简单的Backbone应用程序没有捕获表单提交并对其进行操作。我有一个坐落在Rails上的应用程序,它只是简单地输出JSON。
我的应用程序试图重新创建James Yu的CloudEdit和Jérôme Gravel-Niquet的Todo应用程序。 我只在创建新歌曲对象时遇到问题。 当backbone应该处理表单数据并将其添加到有序列表中时,Rails会接收到POST请求并响应JSON和HTML。 我正在使用ICanHaz Gem进行JS模板。
有任何想法吗?
//主要应用程序视图
window.AppView = Backbone.View.extend({
el: $("#songs_app"),
events: {
"submit form#new_song": "createSong"
},
initialize: function(){
_.bindAll(this, 'addOne', 'addAll');
Songs.bind('add', this.addOne);
Songs.bind('reset', this.addAll);
Songs.bind('all', this.render);
Songs.fetch(); //This Gets the Model from the Server
},
addOne: function(song) {
var view = new SongView({model: song});
this.$("#song_list").append(view.render().el);
},
addAll: function(){
Songs.each(this.addOne);
},
newAttributes: function(event) {
var new_song_form = $(event.currentTarget).serializeObject();
//alert (JSON.stringify(new_dog_form));
return { song: {
title: new_song_form["song[title]"],
artist: new_song_form["song[artist]"]
}}
},
createSong: function(e) {
e.preventDefault(); //This prevents the form from submitting normally
var params = this.newAttributes(e);
Songs.create(params);
//TODO - Clear the form fields after submitting
}
});
// 歌曲视图
window.SongView = Backbone.View.extend({
tagName: "li",
initialize: function(){
},
collapse: function(){
$(this.el).removeClass("active");
},
render: function(){
var song = this.model.toJSON();
$(this.el).html(ich.song_item(song));
return this
},
});
// index.html.erb
<div id="songs_app">
<h1 id="logo">Test App</h1>
<ol id="song_list">
</ol>
</div>
<%= render 'form' %>
<script id="song_item" type="text/html"></script>
<script id="similar_song_item" type="text/html"></script>
// 歌曲控制器
def create
@song = Song.new(params[:song])
respond_to do |format|
if @song.save
format.html { redirect_to(@song, :notice => 'Song was successfully created.') }
format.json { render :json => @song, :status => :created, :location => @song }
else
format.html { render :action => "new" }
format.json { render :json => @song.errors, :status => :unprocessable_entity }
end
end
end