Backbone.js attach view to multiple elements

2019-04-08 03:57发布

I am rather new to backbone, so its possible that i am violating the very essence of backbone in doing this. Suggestions are appreciated:

I have made a wall sort of system. So there is a form that can be used to post updates on the wall.

Each update can have comments on them. I am showing 10 updates at a time. So there are 10 comment forms. So I have a view:

    CommentForm=Backbone.View.extend({
initialize:function(messageView){

},
events:{
    "submit":"postcomment"
},
showMessage:function(data){
      if(data.success)
            type="success";
               else
            type="error";
           message=data.error?data.error:"Update posted successfully";
           $messageContainer=$this.prev();
           console.log($this);
           var html="<div class='alert alert-"+type+"'>"+message+"</div>";
            $($messageContainer).html(html);
},
postcomment:function(){
        $this=$(this.el);

        $.post(baseUrl+"/portal/post-comment",$this.serialize(),this.showMessage,"json");
        return false;
}


   });

Now I create an instance to it as follows:

  commentFormView= new CommentForm({el:$(".comment-form form")});

Note that .comment-form is a div. There are multiple such elements. The event handler gets attached to all the comment forms just fine. But when I use $this=$(this.el); it always refers to the first comment form. How do I solve this. $(this.el) should refer to the current instance of comment form, where the event was triggered and not the first one

2条回答
2楼-- · 2019-04-08 04:33

One way would be to create a new view for each element using something like this.

$(".comment-form form").each(function() {
    new CommentForm( { el: $(this) } );
});

Edit There is another (better?) way. Because the event handler gets the raw event as its first parameter, you can write the handler postcomment like this:

postcomment:function(evt){
   // ...
}

Then you can use $(evt.srcElement) to get the actual element.

postcomment:function(evt){
   $this = $(evt.srcElement);
   // ...
}
查看更多
我想做一个坏孩纸
3楼-- · 2019-04-08 04:59

$('.comment-form form') will return an array of all the matching form elements. You need to iterate through that array and create a view for each element, like dbaseman showed.

Also, instead of doing

$this=$(this.el)

backbone views already provide a jquery wrapped el:

this.$el
查看更多
登录 后发表回答