2014-12-05 60 views
0

事件工作在附加鉴于骨干事件不附加视图

这里不起作用是视图的方法:

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() { 
..... 
} 

谢谢)

+0

控制台中是否有错误? – 2014-12-05 10:28:45

回答

1

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

您正在使用的profileView有实例,你在什么地方初始化像

var profileView = new ProfileView(); 

ProfileView延伸从Backbone.View,当你初始化它会delegate events 并将其绑定到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); 
} 

和ProfileView:

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); 
    } 

} 

and ProfileView中:

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 
} 

不要忘记管理ProfileView删除和事件解除绑定,当你不再需要它。

0

这是由于你的 “厄尔尼诺” 属性,即乌尔追加应该是你EL

eg: el : "#container" // must set 

    <div id="container"> 
     . 
     . 
     . 
     . 
    <div id="new-appended-views"></div> 
    . 
    . 
    </div> 
内部视图

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