簡體   English   中英

視圖上的骨干重綁定事件

[英]Backbone rebinding events on a view

我有兩個視圖,一個代表客戶端視圖,另一個代表個人客戶端視圖。 我在客戶端視圖中綁定了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;
  }
});

編輯 :這里我試圖在創建的視圖(具有事件的視圖delegateEvents()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 我對這個插件不熟悉,看起來它沒有一個未經說明的版本,所以我讀不太清楚。

還有其他建議嗎?

您可以使用視圖的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() { ...

暫無
暫無

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

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