2013-04-10 93 views
0

我正在使用jQuery工具提示插件,該插件需要使用jQuery克隆函數來填充自動生成的工具提示。對於我正在開發的項目,我沒有控制何時啓動工具提示,也沒有可用的回調,因此我使用jQuery .on('mouseenter')來初始化我的事件。骨幹視圖 - 在鼠標上創建時不輸入事件

任何我放在初始化函數的作品,但我的點擊事件不會觸發。從我讀過的內容來看,如果el被定義,那麼標準事件(click)應該被自動綁定,但是這並沒有發生,並且據我所知,這應該是正確的。

的javascript:

Lot = Backbone.View.extend({ 
    initialize: function(){ 
     this.wrapper = $(this.$el).find('.childDiv'); 
     $(this.$el).css('background-color', 'blue'); 
     console.log('init'); 
    }, 
    events: { 
     'click .showChild': 'showfunction' 
    }, 
    showfunction:function(e){ 
     this.wrapper.slideToggle('fast'); 
    } 
}); 

//gives the auto generated tooltip a class, otherwise it would be classless 
$.balloon.defaults.classname = "balloon"; 

//tooltip needs content passed in, the tooltip creator recommends using clone 
$('#showParent') 
    .balloon({contents: $('.tooltip-content').clone(), position: "bottom right" }); 

// this may look redundant, but I do not have access to the initialize function 
$('#showParent').on('mouseenter', function() { 
    console.log('mouse enter'); 
    lots = new Lot({el: $('.balloon .tooltip-content')}); 
}); 

HTML:

<button id="showParent">Hover</button> 
<div id="wrapper"> 
    <div class="parentDiv tooltip-content"> 
     <h1> Some text to test parent</h1> 
     <button class="showChild">Click</button> 
     <div class="childDiv"> 
      <h2> here is a child div</h2> 
     </div> 
    </div> 
</div> 

這裏是一個小提琴:http://jsfiddle.net/KFkjZ/

任何INSITE,爲什麼事件可能不具有約束力認識

+0

爲什麼你'$(這$ EL)'當你可以只使用'this。$ el'? – 2013-04-10 18:21:48

+0

因爲一個「知道」骨幹的人與世界分享了他們的教程,但顯然他們並不知道這一點,或者有他們的理由,並忽略提及它..感謝指出這一點,現在我想到了,這是有道理的,爲什麼它會起到作用。 – ckdesign 2013-04-10 18:48:37

回答

0

這是因爲jQuery插件使用該克隆並在第一次顯示時將其附加到HTML的body。這會打破您的Lot視圖的事件處理程序(因爲它意味着Backbone附加事件處理程序的範圍不再相關)。它打破了封裝

一種選擇是附加文檔級事件來處理你想要的方式點擊:

$(document).on('click', '.showChild', function (e) { 
    console.log('clicked'); 
    $(this).slideToggle('fast');  
}); 
+0

這是事實,是否有重新綁定事件?麻煩的是我需要使用主幹,我發佈的是一個小用例,我真的需要骨幹來處理click事件,以便可以在模型上觸發更改事件並提示其他視圖進行更新。 – ckdesign 2013-04-10 20:37:22