模型没有被推入backbonejs的集合

时间:2014-10-28 10:32:42

标签: javascript jquery backbone.js backbone-collections backbone-model

jsfiddle

此时我尝试使用this tutorial创建一个消息客户端,当在该字段中键入新消息并单击添加按钮时,该视图应该会更新。 出于某种原因," addMessage"事件未能将新模型添加到集合中。



var messagesjson = [
  { 
    id: 3,
    message: "This is the message",
    sender: "gabriel",
    receiver: "gabriel",
    has_been_read: false,
    has_been_reported: false,
    created_at: "2014-10-23T19:55:20+0200",
    is_friend: false
  },
  {
    id: 5,
    message: "I'm loving this ",
    sender: "gabriel",
    receiver: "gabriel",
    has_been_read: true,
    has_been_reported: false,
    created_at: "2014-10-23T20:02:34+0200",
    is_friend: false
  }];

var MessageModel = Backbone.Model.extend({
  defaults:
  {
    id: 3,
    message: "This is the message",
    sender: "gabriel",
    receiver: "gabriel",
    has_been_read: false,
    has_been_reported: false,
    created_at: "2014-10-23T19:55:20+0200",
    is_friend: false
  }
});

var MessageView = Backbone.View.extend({
  tagName: "div",
  className: "listview",
  template: $('#messageTemplate').html(),
  render: function()
  {
    var tmpl = _.template(this.template);
    console.log(this.model);
    this.$el.html(tmpl(this.model.toJSON()));
    return this;
  }
});

var MessageCollection = Backbone.Collection.extend({
  model: MessageModel
});

var MessageCollectionView = Backbone.View.extend({
  el: $('#messages'),
  initialize: function()
  {
    this.collection = new MessageCollection(messagesjson);
    this.render();
    this.collection.on("add", this.renderMessage, this);
  },
  render: function()
  {
    var that = this;
    _.each(this.collection.models, function(item){
      that.renderMessage(item);
    },this);
  },
  events:{
    "click #add":"addMessage"
  },
  renderMessage: function(item)
  {
    var messageview = new MessageView({
      model: item
    });

    this.$el.append(messageview.render().el);
  },
  addMessage: function(e)
  {
    e.preventDefault();
    var formData = {};

    $("#addMessage").children("input").each(function (i, el) {
      formData[el.id] = $(el).val();
    });

    messagesjson.push(formData);
    this.collection.add(new MessageModel(formData));

    console.log(messagesjson);
  }
});

var messagecollectionview = new MessageCollectionView();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<div id="messages">  
  <form id="addMessage" action="#">
    <div>
      <label for="messageText">Message: </label>
      <input id="messageText" type="text" />
      <button id="add">Add</button>
    </div>
  </form>
</div>

<script type="text/template" id="messageTemplate">
  <a href="#" class="list autoWidth <% if(has_been_read) { %> selected <% } %>">
    <div class="list-content">
      <img src="//www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=20774792" class="icon">
      <div class="data">
      <span class="item-title-secondary fg-gray"><b><%= sender %></b></span>
    </div>
    <span class="tertiary-text">
      <%= message %>
    </span>
    </div>
  </a>
</script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您将所有新模型的ID设置为3,因为默认哈希包含id: 3。该集合认为它与已具有该ID的模型具有相同的模型。

首先,您需要使用id:null更改默认值:

var MessageModel = Backbone.Model.extend({
    defaults:{
        id: null,
        message: "This is the message",
        sender: "gabriel",
        receiver: "gabriel",
        has_been_read: false,
        has_been_reported: false,
        created_at: "2014-10-23T19:55:20+0200",
        is_friend: false
    }
});

然后你需要修复获取formData的代码。首先,您使用的是jQuery children()方法,该方法只关注直接的孩子。这意味着你永远不会得到表单内的输入,因为有一个中间div。您可以使用find

其次,您需要确保formData具有名为message的属性,以便它可以覆盖默认的message: "This is the message"。我会在输入元素中添加名称属性message,并像formData[el.name] = $(el).val();一样使用它。 (您稍后可以使用其中一个jquery serializeObject插件以这种方式自动序列化所有输入元素。)

所以addMessage看起来像这样:

addMessage: function(e){
    e.preventDefault();
    var formData = {};

    $("#addMessage").find("input").each(function (i, el) {
        formData[el.name] = $(el).val();
    });                

    messagesjson.push(formData);
    this.collection.add(new MessageModel(formData));
}

您可以在this fiddle

中试用