骨干事件和元素

时间:2013-09-16 18:50:26

标签: javascript backbone.js

我在app中有两个元素(输入)。当我点击它时,我希望能够编辑该元素。出于某种原因,当我编辑第一个输入时,它会编辑两个值。显然,我不了解el或事件或两者兼而有之。谢谢你的帮助。

$(function(){

  var AddressBook = Backbone.Model.extend({
    defaults: function() {
      return {
         name: "No contact name provided",
         email: "No email address provided"
      };
    },
  });

  var AddressBookList = Backbone.Collection.extend({
    model: AddressBook,
    localStorage: new Backbone.LocalStorage("address-book")
  });

  AddressBookList.comparator = function(entry) {
    return AddressBookList.get("name");
  };

  var AddressBookEntries = new AddressBookList;

  var AddressBookView = Backbone.View.extend({
    tagName:  "li",
    template: _.template($('#item-template').html()),
    events: {
      "click .toggle"   : "toggleDone",
      "dblclick .name"  : "edit",
      "dblclick .email"  : "edit",
      "click a.destroy" : "clear",
      "keypress .edit"  : "updateOnEnter",
      "blur .edit"      : "close"
    },

    // The TodoView listens for changes to its model, re-rendering. Since there's
    // a one-to-one correspondence between a **Todo** and a **TodoView** in this
    // app, we set a direct reference on the model for convenience.
    initialize: function() {
      this.listenTo(this.model, 'change', this.render);
      this.listenTo(this.model, 'destroy', this.remove);
    },

    render: function() {
      this.$el.html(this.template(this.model.toJSON()));
      this.input = this.$('.edit');
      return this;
    },

    // Toggle the `"done"` state of the model.
    // toggleDone: function() {
//       this.model.toggle();
//     },

    // Switch this view into `"editing"` mode, displaying the input field.
    edit: function() {
        console.log(this.$el);
      this.$el.addClass("editing");
      this.input.focus();
    },

    // Close the `"editing"` mode, saving changes to the todo.
    close: function() {
      var value = this.input.val();
      if (!value) {
        this.clear();
      } else {
        this.model.save({name: value, email: value});
        this.$el.removeClass("editing");
      }
    },

    // If you hit `enter`, we're through editing the item.
    updateOnEnter: function(e) {
      if (e.keyCode == 13) this.close();
    },

    // Remove the item, destroy the model.
    clear: function() {
      this.model.destroy();
    }

  });

  var AppView = Backbone.View.extend({

    el: $("#address-book"),
    events: {
      "click #save-entry":  "createAddressBookEntry",
      "click #clear-completed": "clearCompleted",
      "click #toggle-all": "toggleAllComplete"
    },

    initialize: function() {

      this.input = this.$("#save-entry");
      this.listenTo(AddressBookEntries, 'add', this.addOne);
      this.listenTo(AddressBookEntries, 'reset', this.addAll);
      this.listenTo(AddressBookEntries, 'all', this.render);

      this.footer = this.$('footer');
      this.main = $('#main');

      AddressBookEntries.fetch();
    },

    render: function() {
      if (AddressBookEntries.length) {
        this.main.show();
      } else {
        this.main.hide();
      }
    },

    addOne: function(entry) {
      var view = new AddressBookView({model: entry});
      this.$("#contact-list").append(view.render().el);
    },

    addAll: function() {
      AddressBookEntries.each(this.addOne, this);
    },

    createAddressBookEntry: function(e) {
      var entry = AddressBookEntries.create({name: $("#name").val(), email: $("#email").val()});
      $("#email").val('');
      $("#name").val('');
    },
  });

  var App = new AppView;

});


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Backbone.js Todos</title>
  <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" media="screen" title="no title" charset="utf-8">
  <link rel="stylesheet" href="css/narrowJumbotron.css" type="text/css" media="screen" title="no title" charset="utf-8">
  <link rel="stylesheet" href="css/app.css" type="text/css" media="screen" title="no title" charset="utf-8">
</head>

<body>

    <div class="container">
          <div class="header">
            <ul class="nav nav-pills pull-right">
              <li class="active"><a href="#">Home</a></li>
              <li><a href="#">About</a></li>
              <li><a href="#">Contact</a></li>
            </ul>
            <h3 class="text-muted">Address Book</h3>
          </div>

          <div class="jumbotron">
            <h1>Jumbotron heading</h1>
            <p class="lead"></p>
            <p><a class="btn btn-lg btn-success" href="#">Sign up today</a></p>
          </div>

          <div class="row marketing">
            <div class="col-lg-6">
                <div id="address-book">

                  <header>
                  <input id="name" type="text" placeholder="Name">
                  <input id="email" type="text" placeholder="Email">
                  <a id="save-entry" class="btn btn-lg btn-success" href="#">Save</a>
                  </header>

                  <section id="main">
                    <ul id="contact-list"></ul>
                  </section>
                </div>

            </div>
        </div>
    </div>

  <script src="js/jquery-1.10.1.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="js/underscore.js" type="text/javascript" charset="utf-8"></script>
  <script src="js/backbone.js" type="text/javascript" charset="utf-8"></script>
  <script src="js/backbone.localStorage-min.js" type="text/javascript" charset="utf-8"></script>
  <script src="js/app.js" type="text/javascript" charset="utf-8"></script>

  <!-- Templates -->

  <script type="text/template" id="item-template">
    <input class="name edit" type="text" value="<%- name %>" />
    <input class="email edit" type="text" value="<%- email %>" />
  </script>

  </body>
</html>

1 个答案:

答案 0 :(得分:1)

您的每个输入都有编辑类吗?试试这个......

close: function(e) {
  var $self = $(e.currentTarget);
  var value = $self.val();

  if ($.trim(value)) {
    this.clear();
  } else {

    if ($self.hasClass('name')) {
      this.model.save({name: value});
    } else {
      this.model.save({email: value});
    }

    this.$el.removeClass("editing");
  }
},