Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js attach view to multiple elements

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

like image 215
SoWhat Avatar asked Oct 03 '12 03:10

SoWhat


2 Answers

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);
   // ...
}
like image 192
McGarnagle Avatar answered Sep 18 '22 22:09

McGarnagle


$('.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
like image 33
Cezary Wojtkowski Avatar answered Sep 21 '22 22:09

Cezary Wojtkowski