0

I have a problem which I don't know is related to the meteor implementation of events or to Javascript events in general.

I have a textbox attached to a "change" event. Next to it, I have a button attached to a "click" event.

When I do a change in the textbox and click the button, the click event does not fire (only the change event does). So I have to click the button two times for the click event to fire.

In Firefox, it works if I attach a mousedown event instead of the click event to the button. In Chrome it doesn't work either ways.

Minimal code reproducing the problem:

JAVASCRIPT: testevent.js

if (Meteor.isClient) {
  Session.set("something", "something");

  Template.hello.foo = function() {
    return Session.get("foo");
  };

  Template.hello.something = function() {
    return Session.get("something");
  }
  Template.hello.events({
    'click .buttonid' : function () {
      console.log("click !");
    },
    'change  .textid' : function (e,t) {
      console.log("change !");
      var bar = e.target.value;
      Session.set("foo",bar);
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

HTML: testevent.html

<head>
  <title>testevent</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  <input type="text" class="textid" value="{{foo}}"/>
  <input type="button" class="buttonid" value="{{something}}" />
</template>

When I replace class with id the click event fire, but when I have multiple fields with the same id the events work only on one field.

4

1 回答 1

1

这个问题与hello.foo

Template.hello.foo = function() {
  return Session.get("foo");
};

foo以及 的值用于响应式填充文本输入的事实。如果您删除该hello.foo功能,一切都会按预期工作。当用户单击按钮时,会触发更改事件,该事件会设置"foo"会话变量,从而导致模板重新呈现。我认为渲染过程会清除剩余的事件队列,因此单击处理程序永远不会触发。

有几种方法可以解决此问题。一种简单(但粗略)的方法就是延迟在更改事件处理程序中设置会话变量。例如:

Meteor.setTimeout(function(){Session.set("foo", bar);}, 100);

显然,您需要选择适当的延迟,这可能取决于浏览器/数据。或者,您可以将文本输入放在它自己的模板中。例如:

<template name="hello">
  {{> helloText}}
  <input type="button" class="buttonid" value="{{something}}" />
</template>

<template name="helloText">
  <input type="text" class="textid" value="{{foo}}"/>
</template>

将事件正确绑定到这个新模板后,您会发现helloText它将单独呈现hello,因此您的事件将被保留。

于 2013-05-29T03:31:37.410 回答