事件在追加视图中不起作用

events doesn't work in appended view

本文关键字:不起作用 视图 追加 事件      更新时间:2023-09-26

events 在主干的附加视图中不起作用

下面是视图的方法:

events: {
  'click .toolbar_ship': 'openProfile'
},
openProfile: function() {
  gameView.$el.append(profileView.render().$el);
}

这是个人资料:

events: {
  'click .object_in_inventory': 'inventoryClick',
  'click .object_in_cell': 'cellClick',
  'click .close_profile': 'closeProfile'
},
render: function() {
  this.$el.html(this.template());
  return this;
},
closeProfile: function() {
  this.$el.remove();
}

首先配置文件被正确附加,点击时所有绑定都工作得很好,但是当我关闭个人资料然后打开一个个人资料时,没有任何点击工作。

我什至不明白为什么它会快乐,我会感谢您的帮助。

下面是点击的示例:

$('.wrapGate').bind('click', function() {
.....
}

谢谢)

您的问题来自openProfile方法的实现。

您正在使用已在某处初始化的profileView实例,例如

var profileView = new ProfileView();

ProfileViewBackbone.View扩展,当您初始化时,它将委派事件并将他们绑定到this.$el.

当你在this.$el上调用jQuery的remove()方法时,它将删除它并解绑所有附加的事件。

下次调用openProfile时,profileView.render().$el将返回您的视图,但没有任何事件。


为了避免这种情况,您需要重构代码。在几种情况下,您可以实现此任务。其中之一是始终使用ProfileView的新实例,例如:

events: {
  'click .toolbar_ship': 'openProfile'
},
openProfile: function() {
  var profileView = new ProfileView();
  gameView.$el.append(profileView.render().$el);
}   

并在配置文件视图中:

events: {
  'click .object_in_inventory': 'inventoryClick',
  'click .object_in_cell': 'cellClick',
  'click .close_profile': 'closeProfile'
},
render: function() {
  this.$el.html(this.template());
  return this;
},
closeProfile: function() {
  this.remove(); // this.remove() is the method of Backbone.View, which will manage removing of view and unbinding of events.
}

另一种解决方案可能是在用户单击关闭配置文件时隐藏配置文件视图

events: {
  'click .toolbar_ship': 'openProfile'
},
openProfile: function() {
  if (this.profileView) {
      this.profileView.$el.show(); // your custom showing logic
  } else {
      this.profileView = new ProfileView(); // caching profileView
      gameView.$el.append(profileView.render().$el);
  }
}   

并在配置文件视图中:

events: {
  'click .object_in_inventory': 'inventoryClick',
  'click .object_in_cell': 'cellClick',
  'click .close_profile': 'closeProfile'
},
render: function() {
  this.$el.html(this.template());
  return this;
},
closeProfile: function() {
  this.$el.hide(); // your custom showing logic
}

不要忘记管理配置文件视图删除和事件解除绑定,当您不再需要它时。

这是由于您的"el"属性,您正在附加的视图应该在您的 el

eg: el : "#container" // must set
    <div id="container">
      .
      .
      .
      .
   <div id="new-appended-views"></div>
     .
     .
    </div>

这些事件将适用于所有新附加的视图