你有两个专业的选择。如果您有其他可能删除子元素的东西(如另一个视图),您可以检查 DOM 的状态是否良好,或者您可以为视图设置一个标志,该标志效率高很多倍(但更难管理)。
检查 DOM:
events: {
'click .share-widget': 'showEmbededCode'
},
showEmbededCode: function(e){
/* Check to see if the copy-widget already exists as a child */
if($("#link-options-dropdown .copy-widget").length===0){
var emebededCode = '<div class="inframe-container"></div>';
var widgetKey = $(e.currentTarget).attr("data-widgetKey");
var iframe = '<iframe src="'+widgetKey+'/widget" width="100%" height="100%" frameborder="0"></iframe>';
var copy = '<p class="copy-widget">Copy and paste the code below to your blog or website. If needed adjust the width or/and height (f.e. width="400px"): </p>';
$('#link-options-dropdown').append(copy);
$('#link-options-dropdown').append(emebededCode);
$('.inframe-container').text(iframe);
}
}
设置标志:
initialize: function(){
...
_.bindAll(this, "showEmbededCode");/* Makes sure `this` refers to View (Part of Underscore) */
},
events: {
'click .share-widget': 'showEmbededCode'
},
embededCodeDrawn: false,
showEmbededCode: function(e){
/* Check to see if the flag is set */
if(this.embededCodeDrawn){
var emebededCode = '<div class="inframe-container"></div>';
var widgetKey = $(e.currentTarget).attr("data-widgetKey");
var iframe = '<iframe src="'+widgetKey+'/widget" width="100%" height="100%" frameborder="0"></iframe>';
var copy = '<p class="copy-widget">Copy and paste the code below to your blog or website. If needed adjust the width or/and height (f.e. width="400px"): </p>';
$('#link-options-dropdown').append(copy);
$('#link-options-dropdown').append(emebededCode);
$('.inframe-container').text(iframe);
this.embededCodeDrawn = true; /* Make sure it isn't drawn again */
}
}