'/> '/> 如何在Backbone.js中添加mouseover事件 | 所有编程讨论 | zhouni.net

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


M试着给 mouseover 在我看来Backbone的事件中,这是我的看法:

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

12819
2017-07-05 12:58


起源

你以正确的方式绑定。你检查过那个元素真的被分配了主类吗? - Ivan Ivanić
Ya元素正在获得主要类,而不是问题是什么 - XMen


答案:


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

试试这个:

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


13
2017-07-05 14:03



嗨,尝试了你的答案,但鼠标悬停不工作,请检查我试过的问题。 - XMen
啊......是的从事件中删除选择器。文档提到这一点:“省略选择器会导致事件绑定到视图的根元素(this.el)”。更新了答案。 - Heikki
好的,非常感谢它的工作。 - XMen