视图上的骨干重绑定事件

时间:2012-02-21 15:06:25

标签: javascript backbone.js

我有两个视图,一个代表客户端视图,另一个代表个人客户端视图。我正在绑定客户端视图中的mouseentermouseleave事件,以淡入和淡出图像上的叠加层。它本身就可以正常工作。但是,我也使用jQuery插件来做旋转木马效果(插件here)。启用后,我的自定义事件将不再有效。在初始化插件后,有什么方法可以委托客户端视图事件吗?这是我第一次使用Backbone,所以我可能也会做其他错误。

以下是代码:

// Client View
window.ClientView = Backbone.View.extend({
  tagName: 'li',
  template: _.template($("#client-template").html()),
  className: 'client-thumb',

  events: {
    "mouseenter": "fadeOutOverlay",
    "mouseleave": "fadeInOverlay"
  },

  initialize: function() {
  },

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

  fadeOutOverlay: function() {
    $(this.el).find(".slider-image-overlay").fadeOut('fast');
  },

  fadeInOverlay: function() {
    $(this.el).find(".slider-image-overlay").fadeIn('fast');
  }

});

// Clients View
window.ClientsView = Backbone.View.extend({
  el: "#clients",

  initialize: function() {
    this.collection.bind('all', this.render, this);
  },

  render: function() {
    var $clients = $("<ul class='clearfix'></ul>");
    _.each(this.collection.models, function(client) {
      var view = new ClientView({model: client});
      $clients.append(view.render().el);
    });

    $(this.el).hide().append($clients).fadeIn().scrollingCarousel();

    return this;
  }
});

编辑:我在这里尝试delegateEvents()创建的视图(包含事件的视图):

App.View.ClientsView = Backbone.View.extend({
  el: "#clients",

  initialize: function() {
    this.collection.bind('all', this.render, this);
  },

  render: function() {
    var $clients = $("<ul class='clearfix'></ul>");
    var views = [];
    _.each(this.collection.models, function(client) {
      var view = new App.View.ClientView({model: client});
      views.push(view); // Store created views in an array...
      $clients.append(view.render().el);
    });

    $(this.el).hide().append($clients).fadeIn().scrollingCarousel({
      // Use the plugin's callback to try to delegate events again
      afterCreateFunction: function() {
        _.each(views, function(view){
          view.delegateEvents();
        });
      }
    });

    return this;
  }
});

试过这个,但似乎没有用?我做得对吗?我认为插件比DOM更多。看起来它正在触及我尝试绑定的元素以及绑定到mouseentermouseleave。我对这个插件不熟悉,看起来不像是一个没有版本的版本,所以我读得不太好。

还有其他建议吗?

1 个答案:

答案 0 :(得分:19)

您可以使用视图的delegateEvents方法重新绑定事件

用法:myView.delegateEvents()

参考文档http://backbonejs.org/#View-delegateEvents了解更多信息

编辑:

此插件绑定并取消绑定mouseenter / leave而不使用命名空间 - 打开插件脚本并将命名空间添加到事件绑定和解除绑定。

将这些修复程序应用于每次出现这些修复程序,即使没有delegateEvents()

也应该没问题

r.unbind("mouseenter"); =&gt; r.unbind("mouseenter.carousel"); r.unbind("mouseleave"); =&gt; r.unbind("mouseleave.carousel");

r.mouseenter(function() { ... =&gt; r.bind('mouseenter.carousel', function() { ... r.mouseleave(function() { ... =&gt; r.bind('mouseleave.carousel', function() { ...

相关问题