我的视图中的 Backbone.js 事件被多次触发 [英] Backbone.js events in my views being triggering multiple times
问题描述
我可能对如何实现backbone.js有误解,因为我所有支持多个模型的视图(例如,可以显示多个产品的产品"视图)都会将事件发送到每个视图在该会话中创建.
I may have a misunderstanding on how to implement backbone.js, because all of my views that support multiple models (for example, a "Product" view that that can display multiple products), will send events to every view that was created in that session.
因此,在下面的示例中,当我单击 #redirect_product 链接时,会根据我看到的产品数量多次调用redirect_product".如果我浏览了 5 个产品,在第 6 次点击时,我会收到 6 个提醒.
So in the example below, when I click the #redirect_product link, the "redirect_product" is called multiple times depending on how many products i've seen. If I've viewed 5 products, on the 6th click I will get 6 alerts.
这是怎么回事?
505 /****************PRODUCT VIEW****************/
506 App.Views.Product = Backbone.View.extend({
507 el: $('#content_sec'),
508
509 events: {
510 "click #redirect_product": "redirect_product",
511 },
512
513 initialize: function(options) {
514 this.model = this.options.model;
515 this.render();
516
517 },
518
519 render: function() {
520 $(this.el).empty();
521 $('#product_detail_template').tmpl(this.model.toJSON()).appendTo($(this.el));
522
523
524 //Activate facebook buttons
525 if (typeof FB != "undefined"){
526 FB.XFBML.parse(document.getElementById('item_share'))
527 }
528
529 wishlist.init();
530 return this;
531 },
532
533 redirect_product: function() {
534 //Send data on what product being clicked by whom
535 alert('hi');
536
537
538 //Open new window with product for user
539 var external_link = this.model.get('product').attributes['External Link'];
540 window.open(external_link, "external_site");
541
542 },
543 });
推荐答案
我认为问题在于您对所有视图使用相同的 el
.
The problem, I think, is that your using the same el
for all your views.
创建新产品时,请执行以下操作:
When you create a new Product, do something like this:
$('#content_sec').append('<div class="productView"></div>');
var product = new Product();
var view = new ProductView({model: product, el: $('.productView:last')});
一旦每个产品都有自己的范围,事件就会按预期工作.
Once each product has its own scope, then the events will work as expected.
这篇关于我的视图中的 Backbone.js 事件被多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!