LittleFunny
LittleFunny

Reputation: 8375

Backbone.js: Why does the event being fired multiple times

I am very new in backbone.

I am trying to have an event on the view object. When I add the event with alert box message, the event being called multiple times.

This is my code i written:

var photo = Backbone.Model.extend({

    initialize : function () {
        imageURL = 'no url',
        data = "";
        width = 0,
        height = 0
    },

    close: function () {
        this.destroy();
        this.view.remove();
    }
});  

var photoCollection = Backbone.Collection.extend({
    model : photo,
    url   : '/photos'
});

var photoView = Backbone.View.extend({
    model: photo,
    el: 'body',
    initialize: function () { 
    },
    events : {
        'click img':'imageClicked'
    },
    imageClicked : function () {
        alert("ASDF");
    },
    resize: function (d, width, height) {

        var image = new Image();
        image.src = d;

        $(image).prop('src', d);
        $(image).prop('width', width + 'px');
        $(image).prop('height', height + 'px');

        $(this.el).append('<img src="'+d+'" style="float:left; width:'+width+'px; height:'+height+'px" />');
        return this;
    }})

;

The code I use to create the view instance is here

                    return collection.each(function (photo) {
                    var pView = new photoView({ el: 'body' });

                    pView.resize(  photo.get('data'), parseInt(width /summedRatio * photo.get('aspectRatio')), parseInt(width/summedRatio));
                });

Upvotes: 0

Views: 78

Answers (1)

msapkal
msapkal

Reputation: 8346

Since you are calling the constructor/initializing the photoView every time, multiple events are getting fired.

Avoid initializing this in each loop.

var pView = new photoView({ el: 'body' });

Updated anwser

var photoView = Backbone.View.extend({
    model: photo,
    el: 'img',
    initialize: function () { 
    },
    events : {
        'click img':'imageClicked'
    },
    imageClicked : function () {
        alert("ASDF");
    },
    resize: function (d, width, height) {

        var $image = this.$(el);
        $image.attr('src', d);
        $image.attr('width', width + 'px');
        $image.attr('height', height + 'px');

        $('body').append('<img src="'+d+'" style="float:left; width:'+width+'px; height:'+height+'px" />');
        return this;
    }});

Upvotes: 1

Related Questions