Backbone.js attaches a view to multiple elements

I am new to the spine, so it’s possible that I violate the very essence of the spine in this. Suggestions are welcome:

I created a wall system. Thus, there is a form that can be used to post updates on the wall.

Each update may contain comments on them. I am showing 10 updates at a time. So there are 10 comments. 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 for it as follows:

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

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

+6
source share
2 answers

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

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

There is another way (better?). Since the event handler receives the original event as its first parameter, you can write a postcomment handler as follows:

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

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

 postcomment:function(evt){ $this = $(evt.srcElement); // ... } 
+7
source

$ ('. comment-form form') will return an array of all the relevant form elements. You need to go through this array and create a view for each element, as dbaseman showed.

Also, instead of doing

 $this=$(this.el) 

Backbone views already provide jquery wrapped el:

 this.$el 
+1
source

Source: https://habr.com/ru/post/926803/


All Articles