Backbone不会绑定表单提交

时间:2011-07-25 01:53:29

标签: json ruby-on-rails-3 backbone.js

我的超级简单骨干应用程序并没有提交表单提交并采取行动。我有这个应用程序坐在铁轨上,只是吐出JSON。

我的应用是尝试重新创建James Yu's CloudEdit& Jérôme Gravel-Niquet's Todo's App。我只是在创建新的Song对象时遇到问题。 Rails选择POST并使用JSON&主干应该处理表单数据并将其添加到有序列表中的HTML。我正在使用ICanHaz Gem for JS Templates。

有什么想法吗?

//主要应用程序视图

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">
<div id='{{id}}'>
    <div class='listTrackContent'>
        <a href="#show/{{id}}">{{title}} by {{artist}}</a>
        <ol class="{{id}}">
        </ol>
    </div>
</div>
</script>

<script id="similar_song_item" type="text/html">
<li>
    <a href="{{trackUrl}}">{{title}}</a> by <a href="{{artistUrl}}">{{artist}}</a>
</li>
</script>

// songs_controller.rb

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

1 个答案:

答案 0 :(得分:9)

问题最终成为我表单的位置。我在#songs_app之外渲染。

确保所有骨干控制的内容都在“el”内。 = X