问题描述
我可能就如何落实Backbone.js的一种误解,因为我所有的观点,即支持多种模式(例如,产品认为,可以同时显示多个产品),将发送事件,这是每个视图该会话中创建。
因此,在下面的例子中,当我点击#redirect_product链接时,redirect_product取决于多少产品我见过多次调用。如果我浏览过5个产品,6日点击我会得到6警报。
这是怎么回事?
505 / ****************产品视图**************** /
506 App.Views.Product = Backbone.View.extend({
507 EL:$('#content_sec'),
508
509事件:{
510点击#redirect_product:redirect_product
511},
512
513初始化:功能(选件){
514 this.model = this.options.model;
515 this.render();
516
517},
518
519渲染:功能(){
520 $(this.el).empty();
521 $('#product_detail_template')TMPL(this.model.toJSON())appendTo($(this.el))。。
522
523
524 //激活的Facebook按钮
如果525(typeof运算FB!=未定义){
526 FB.XFBML.parse(的document.getElementById('item_share'))
527}
528
529 wishlist.init();
530回本;
531},
532
533 redirect_product:功能(){
534 //发送被点击由谁什么样的产品数据
535的警报('你好');
536
537
538产品用户//打开新窗口
539 VAR external_link = this.model.get(产品)的属性['外部链接'];
540 window.open(external_linkexternal_site);
541
542},
543});
的问题,我想,那是你使用相同的报
为您的所有意见。
当你创建一个新的产品,做这样的事情:
$('#content_sec')追加('< DIV CLASS =ProductView的>< / DIV>');
变种产品=新产品();
VAR视图=新的ProductView({模式:产品,EL:$('。ProductView的:去年')});
一旦每个产品都有自己的适用范围,那么事件将正常工作。
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.
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.
What's going on here?
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 });
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的事件被触发多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!