9

我有一个主干视图,它为传递给它的每个模型创建一个新的 div。但是,我无法在视图上触发任何类型的事件(单击 a.change-status),我认为这是因为其中的元素也是从模板生成的。请让我知道是否有办法解决这个问题。

var videoDivView  = Backbone.View.extend({
el: '<div class="vendor-video" />',
initialize: function(){
    _.bindAll(this);
    this.render();
    this.model.on('change:published', this.enableSaveButton);
},
events: {
    'click a.change-status'     : 'changeVideoStatus'
},
template: video_tmpl,
render: function(){
    this.$el.attr("id", 'video-'+this.model.id);
    this.$el.html(this.template(this.model.toJSON()));
    this.$el.data('status', video_statuses[this.model.get('published')]);
},
changeVideoStatus: function(e) {
    console.log(this.model);
    return false;   
}, 
enableSaveButton: function() {
    $('#save-changes').removeClass('disabled').removeAttr('disabled');
}
});

示例模板如下所示:

<script id="single-video-tmpl" type="text/x-jquery-tmpl">
<div>
    <div class="video-info">
        <span class="video-title"><%=video_title%></span>
        <div class="bottom-info">
            <a href="#<%=id%>" class="change-status"></a>
        </div>
    </div>

</div>
</script>
4

4 回答 4

12

this.delegateEvents()在渲染新内容后尝试。

于 2013-08-28T00:31:54.103 回答
8

There are some things that might be the cause of the problem.

First of all, your el declaration seems to be suspect. If you want a div with that class you just have to define the className attribute since the default for backbone views is div.

Instead of: el: '<div class="vendor-video" />'

just use: className: 'vendor-video'

I don't see any details about your view initialization methods but the best practice is to initialize a view and then render it to the container:

var yourVideoDivView = new videoDivView({model: model});
$("#your-video-container").html(yourVideoDivView.render().el)

also to get the last line work you have to return this; on your render method.

render: function(){
  ...
  return this;
}

About using this.delegateEvents(), you should call this function after your view is already in the DOM otherwise it makes no sense. ie:

$("#your-video-container").html(yourVideoDivView.render().el)
yourVideoDivView.delegateEvents();

delegateEvents() will makes your view events alive again.

于 2013-08-28T09:42:45.703 回答
1

我有一个类似的问题。您可以分两步解决此问题。
- 创建一个tagName视图
- 将您的模板附加到this.$el
这就是全部。它没有this.delegateEvents()

于 2014-10-23T08:56:11.410 回答
0

The issue I observed with tagName and appending using this.$el is, the event listener failed to attach the event for the last element created with selected tagName. But, the problem got solved when using this.delegateEvents() after appending the elements to DOM.

于 2014-11-23T11:21:45.450 回答