Backbone.js:为什么事件被多次触发

时间:2014-03-24 10:00:36

标签: html events backbone.js view

我是骨干的新手。

我正在尝试在视图对象上创建一个事件。当我使用警告框消息添加事件时,该事件被多次调用。

这是我写的代码:

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;
    }})

我用来创建视图实例的代码在这里

                    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));
                });

1 个答案:

答案 0 :(得分:1)

由于您每次都在调用构造函数/初始化PhotoView,因此会触发多个事件。

避免在每个循环中初始化它。

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

更新了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;
    }});