1

我在导航栏中有一个链接(带有 .story 类),如果单击该链接,则会将故事模板呈现到画布 div 中以向用户提供信息。我想在阅读信息后为用户提供删除模板的选项,但是,我无法在模板中的删除“x”上设置点击事件。

我想我知道问题所在。我的 StoryView el 是这样,<div id="story">所以我可以在其中的任何内容上设置事件,但是由于它呈现到另一个未附加到该视图的 div 中,因此我无法将其从该视图中删除。

这是一个显示问题的小提琴。更新,我包含了错误的小提琴。现在修好了。

http://jsfiddle.net/mjmitche/RRXnK/145/

html

<div id="story">
   <a href="#" class="story">click this story link to render into canvas_id but how to set event to remove?</a>
</div>

<div id="canvas_id"></div>

看法

var StoryView = Backbone.View.extend({

  el: $("#story"),

   events: {
      'click .story': 'render', 
       'click .delete': 'test'

    },

     initialize: function() {

    },
   render: function(){
     var template = $('#story_template').html();
    this.template = _.template(template);
    $('#canvas_id').html(this.template());
   },

    test: function() {
   alert("delete"); 
        <!--  click .delete event not triggering -->
    },

    remove: function(){
     alert("how to remove the template");   
        <!-- how to remove template after rendering -->
    }


  });

var story_view = new StoryView();

模板:

<div id="story">
   <a href="#" class="story">click this story link to render into canvas_id but how to set event to remove?</a>
</div>

<div id="canvas_id"></div>

<script id="story_template" type="text/underscore">
"I want to make the x
    after this story clickable to remove the template
    but since it's not within the #story div (which
    is just a navbar in my real app), it's not working"
<span class="delete">X</span>



</script>
4

1 回答 1

2

要理解为什么只能在视图的 el 上监听事件,首先需要了解backbone.js是如何监听事件的。

在主干.js 事件被委托(使用 jQuery 或 Zepto)到视图的el. 在您的情况下,您的视图el#story您的删除事件没有被触发。

您可以做的是,当您单击以呈现模板时,您可以使用setElement重新分配视图的 el ,这也会将视图委托事件移动(重新委托)到新的el((如@muistooshort指出的那样)。

例如

   render: function(){
     var template = $('#story_template').html();
    this.template = _.template(template);
    $('#canvas_id').html(this.template());
       this.setElement($('#canvas_id'));
   },

在您的删除事件中,您可以将您的el背部重新分配给#story元素。

更新jsFiddle

于 2013-02-07T21:09:52.533 回答