【问题标题】:Marionettejs events issueMarionettejs 事件问题
【发布时间】:2014-07-16 12:04:23
【问题描述】:

我正在使用 MarionetteJS v2.0.2,这是我的问题

我在下面有 itemView

var Users = Marionette.ItemView.extend({
    template: 'user.html',
    tagName: 'li',
    attributes: {
        class: 'name'
    },
    initialize: function () {
        //console.log(this);
    },
    events: {
        "click.name": "onClick"
    },
    onClick: function () {
        console.log('click');
    }
});

所以当我在我的事件中写“click.name”时,该事件被触发,但是当我写“click.name”(有一个空格)时它不是。

谁能帮我理解为什么?

【问题讨论】:

  • 据我了解,您尝试点击根 ItemView 节点。只使用 { 'click' : 'onClick' },这不起作用,因为查看委托事件通过选择器查看 $el,因此在您的视图事件中没有 .name 不会触发 - Bacbone 视图 delegateEvents 方法部分 - if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); }.
  • name.click 可以作为木偶中触发器支持的一部分,但我不确定
  • 事件名称没有空格,这些空格与牵线木偶或骨干无关,这些事件被委托给 jQuery,这是一般规则 - 无论是 event 还是 event.namespace - 都没有空格跨度>
  • 能否请您发布更多代码?

标签: backbone.js marionette


【解决方案1】:

正如cmets中提到的,原因

events: {
        "click .name": "onClick"
    },

不起作用的是,通过添加“.name”,您为事件绑定提供了一个选择器,但绑定的范围是视图本身的 el(在您的情况下为 li),因为您分配了“.name” " 类到 li 没有具有该类名的内部项,并且绑定不起作用。

执行“click.name”(无空格)与执行“click”完全一样,只是您为绑定提供了一个命名空间,就 jQuery 而言这是有效的 - http://api.jquery.com/on/#event-names

您可以在没有骨干的情况下看到它是如何工作的。例如采用以下绑定:

//this will work because were listening for click on our li
$("li").on("click", function(){
  console.log("im the jquery handler");
});

 //this will work because were doing the same as before only adding a namespace for our event 
$("li").on("click.name", function(){
  console.log("im the jquery handler");
});

 //this will NOT work because were adding the .name selector and jquery wont find an element with this class in our li element 
$("li").on("click",".name", function(){
  console.log("im the jquery handler");
});

简而言之,就事件而言,您不需要 .name,或者您应该将 .name 类添加到内部元素作为模板的一部分,然后它将与您在问题中提供的代码一起使用。

【讨论】:

    猜你喜欢
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2019-08-03
    相关资源
    最近更新 更多