Backbone.js的重视,以多个元素 [英] Backbone.js attach view to multiple elements
问题描述
我是相当新的中坚力量,所以它可能是我正在违反骨干的本质在做这个。建议是AP preciated:
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.
每个更新可以对他们的意见。我一次显示10更新。因此,有10注释的形式。
所以,我有一个观点:
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")});
注意的.comment形式是一个div。有多个这样的元件。事件处理程序被连接到所有的评论形式就好了。但是当我使用 $此= $(this.el);
它总是指向第一个评论表单。我该如何解决这个问题。 $(this.el)应该是指评论表单的当前实例,在该事件被触发,而不是第一个
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
推荐答案
的一种方法是创建使用这样的事情每个元素的新视图。
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) } );
});
修改还有另一个(更好?)的方式。由于事件处理程序获取的原始事件作为第一个参数,可以编写处理程序 postcomment
是这样的:
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){
// ...
}
然后你可以使用 $(evt.srcElement)
来获得实际的元素。
postcomment:function(evt){
$this = $(evt.srcElement);
// ...
}
这篇关于Backbone.js的重视,以多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!