1

I am newin Backbone, and try to write some simple applications to learn backbone.

The application contains a list of items, and user can add/delete/ items, when user hover one of the item view, the item should changed its color to red,othewise, its color should be black.

    var ItemView = Backbone.View.extend({
        tagName: 'li',
        events: {
            'click a.delete': 'onDelete',
            'mouseover': 'onHoverIn',
            'mouseout': 'onHoverOut'
        },
        template: _.template($('#tpl-item').html()),
        initialize: function () {
            this.model.on("change", this.render, this);
        },
        render: function () {
            var item = this.model;
            this.$el.css("color", item.get("hover") ? "red" : "black").html(this.template(item.toJSON()));
            return this;
        },
        onDelete: function () {
            this.model.destroy();
        },
        onHoverIn: function () {
            this.model.set("hover", true);
        },
        onHoverOut: function () {
            this.model.set("hover", false);
        }
    });

This is the full codes of the app: jfiddle live example

However, it works while I move the mouse over the items one by one slowly, once I move quickly, I found that there may be more than one items are colored with red, which is not expected.

enter image description here

What's going on?

hguser
  • 35,079
  • 54
  • 159
  • 293
  • possible duplicate of [Why can't I reliably capture a mouseout event?](http://stackoverflow.com/questions/7448468/why-cant-i-reliably-capture-a-mouseout-event) –  Jan 05 '15 at 00:16
  • Thanks for your link, but once I check it I found that there is no proper answer. Even I tried to use the `mouseenter` `mouseleave` instead of `mouseout/over`. – hguser Jan 05 '15 at 01:27

1 Answers1

0

because re-render is a heavy and expansive task for browser, and somehow (honestly i dont know the magic behind) it mis-triggered the event.
To reduce the browser reflow, i turn the color manipulation to repaint by adding and remove class >> see here the update code

onHoverIn: function() {
    this.$el.addClass('hover');
    console.log('in: ' + this.model.get('name'));
  },
  onHoverOut: function() {
    this.$el.removeClass('hover');
    console.log('out: ' + this.model.get('name'));
  }
ChinKang
  • 4,212
  • 2
  • 17
  • 29