视图上的骨干重绑定事件

Bra*_*don 7 javascript backbone.js

我有两个视图,一个代表客户端视图,另一个代表个人客户端视图.我绑定了mouseentermouseleave事件在客户视图和缩小图像上叠加褪色.它本身就可以正常工作.但是,我也使用jQuery插件来做旋转木马效果(插件在这里).启用后,我的自定义事件将不再有效.在初始化插件后,有什么方法可以委托客户端视图事件吗?这是我第一次使用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;
  }
});
Run Code Online (Sandbox Code Playgroud)

编辑:我在这里尝试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;
  }
});
Run Code Online (Sandbox Code Playgroud)

试过这个,但似乎没有用?我做得对吗?我认为插件比DOM更多.看起来它正在触及我试图绑定的元素以及绑定到mouseentermouseleave.我对这个插件不熟悉,看起来它没有一个未经说明的版本,所以我读不太清楚.

还有其他建议吗?

Tom*_* Tu 19

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

用法: myView.delegateEvents()

有关详细信息,请参阅文档http://backbonejs.org/#View-delegateEvents

编辑:

此插件在没有命名空间的情况下绑定和取消绑定mouseenter/leave - 打开插件脚本并将命名空间添加到事件绑定和解除绑定.

将这些修复应用于每次出现这些修复,即使没有这些也应该没问题 delegateEvents()

r.unbind("mouseenter");=> r.unbind("mouseenter.carousel"); r.unbind("mouseleave");=>r.unbind("mouseleave.carousel");

r.mouseenter(function() { ...=> r.bind('mouseenter.carousel', function() { ... r.mouseleave(function() { ...=>r.bind('mouseleave.carousel', function() { ...