簡體   English   中英

骨干事件並不總是在el上發生

[英]Backbone event doesn't always happen on `el`

我正在開發自己的Backbone TodoMVC App版本。 到目前為止,這是我的代碼


Backbone事件哈希允許我們將事件偵聽器附加到el相對的自定義選擇器, 或者如果未提供選擇器,則直接附加到el 事件采用鍵值對“ eventName selector”的形式:“ callbackFunction”,並且支持許多DOM事件類型,包括單擊,提交,鼠標懸停,dblclick等。

http://addyosmani.github.io/backbone-fundamentals/

'dblclick': 'showEdit'似乎並沒有發生在el身上。

當我雙擊內部.view-mode div中的某個位置時, $(e.target)是該.view-mode div。

點擊.view-mode

但是,當我在.view-mode但在li內單擊時,應該是$(e.taret)

在.view-mode外部但在li內部單擊

為什么是這樣?


碼:

todo.js

var app = app || {};

app.TodoView = Backbone.View.extend({
  tagName: 'li',

  className: 'list-group-item',

  template: _.template( $('#todo-template').html() ),

  render: function() {
    this.$el.html( this.template(this.model.toJSON()) );
    this.$el.find('.edit-mode').hide();
    this.$el.find('.remove-todo').hide();
    return this;
  },

  events: {
    'click input[type="checkbox"]': 'check',
    'mouseenter': 'showRemove',
    'mouseleave': 'hideRemove',
    'click .remove-todo': 'remove',
    'dblclick': 'makeEditable'
  },

  check: function(e) {
    var id = $(e.target).data('id');
    var model = app.todos.get(id);
    model.save({
      completed: true
    });
  },

  showRemove: function(e) {
    $(e.target).find('.remove-todo').show();
  },

  hideRemove: function(e) {
    $(e.target).find('.remove-todo').hide();
  },

  remove: function(e) {
    var $el = $(e.target);
    var id = $(e.target).data('id');
    var model = app.todos.get(id);
    model.destroy({
      success: function(model) {
        app.todos.remove(model);
        $el.closest('li').remove();
      },
      error: function() {
        alert('Unable to remove todo.');
      }
    });
  },

  makeEditable: function(e) {
    console.log($(e.target).html());
    $(e.target).find('.view-mode').hide();
    $(e.target).find('.edit-mode').show();
  }
});

待辦事項模板

<script type='text/template' id='todo-template'>
  <div class='view-mode'>
    <input 
      type='checkbox'
      data-id='<%= id %>'
      <% if (completed) { %>checked<% } %>
    >
    <%= title %>
    <a data-bypass class='remove-todo' data-id='<%= id %>'>&times;</a>
  </div>
  <div class='edit-mode'>
    <p>Edit Mode</p>
  </div>
</script>

e.target是指事件發生的節點。 事件傳播意味着這可能是您的處理程序附加到的節點的后代。

要獲取事件處理程序附加到的節點,請使用e.currentTarget

請參閱MDN上的Event.currentTarget

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM