如何在Backbone.js中添加mouseover事件

时间:2011-07-05 12:58:37

标签: jquery backbone.js

M试图在我的Backbone视图中提供mouseover事件,这是我的观点:

Backbone.View.extend({
  template :_.template( '<li class="<% if (refertype=="U"){%>info <% }else{%> access<%}%> main"><%=refername%>'+

            '</li>'),
  initialize: function() {
    _.bindAll(this, 'render', 'close');
    this.model.bind('change', this.render);
    this.model.view = this;
  },
    events: {
        "mouseover .main": "mouseovercard"
    },
  // Re-render the contents of the Card item.
  render: function() {
    this.el=this.template(this.model.toJSON());
    $(".cards-list").append(this.el);
  },
    mouseovercard: function() {
        console.log("hello world");
    }
});

但是,当我正在鼠标悬停main课程时,它没有显示hello world,请建议您做什么?

尝试过Heikki答案但鼠标悬停不起作用?

App.Backbone.CardView = Backbone.View.extend({
    tagName: 'li',
    className: 'main',
  initialize: function() {
    _.bindAll(this, 'render');
    this.model.bind('change', this.render);
    this.model.view = this;
  },
    events:{
        "mouseover .main": "mouseovercard"
    },
  // Re-render the contents of the Card item.
  render: function() {
         $(this.el)
            .removeClass('info access')
            .addClass(this.model.get('refertype') == 'U' ? 'info' : 'access')
            .text(this.model.get('refername'));
    $(".cards-list").append(this.el);
  },
    mouseovercard: function() {
        console.log("hello world");
    }
});

1 个答案:

答案 0 :(得分:13)

您正在替换视图绑定事件的根元素。

请改为尝试:

Backbone.View.extend({

    tagName: 'li',

    className: 'main',

    events: {
        'mouseover': 'mouseovercard'
    },

    initialize: function() {
        _.bindAll(this, 'render');
        this.model.bind('change', this.render);
    },

    render: function() {
        $(this.el)
            .removeClass('info access')
            .addClass(this.model.get('refertype') == 'U' ? 'info' : 'access')
            .text(this.model.get('refername'));
        return this;
    },

    mouseovercard: function() {
        console.log('hello world');
    }

});

http://documentcloud.github.com/backbone/#View-extend