【问题标题】:How does meteorjs have string names as functions?meteorjs 如何将字符串名称作为函数?
【发布时间】:2018-12-03 23:36:54
【问题描述】:

查看以下代码sn-p

Template.body.events({
  'submit .new-task'(event) {
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const text = target.text.value;

    // Insert a task into the collection
    Tasks.insert({
      text,
      createdAt: new Date(), // current time
    });

    // Clear form
    target.text.value = '';
  },
});

这段代码 sn-p 取自 MeteorJS 的教程。

通知'submit .new-task'(event)。这怎么可能?如果没有流星,我将如何做同样的事情?

【问题讨论】:

标签: javascript node.js meteor ecmascript-6


【解决方案1】:

这是一个快捷方式:

Template.body.events({
  'submit .new-task': function (event) {
    // ...
  }
});

流星与它没有任何关系。

参考:http://es6-features.org/#MethodProperties

【讨论】:

    【解决方案2】:

    Events 是 EventHandlers 的对象,由以下逻辑解析:

    'submit .new-task' 对于选择器.new-task 被解释为onSubmit,并且该字符串的声明函数是要执行的函数。

    一个 jQuery 等价物是:

    $( ".new-task" ).on( "submit", (event) {
        // Prevent default browser form submit
        event.preventDefault();
    
        // Get value from form element
        const target = event.target;
        const text = target.text.value;
    
        // Insert a task into the collection
        Tasks.insert({
          text,
          createdAt: new Date(), // current time
        });
    
        // Clear form
        target.text.value = '';
      },
    });
    

    一些主要区别在于,在 Blaze 模板事件中,当前模板实例作为第二个参数(未包含在您的示例中)传递,允许您使用 ReactiveVarRactiveDict 获取/设置模板变量。

    使用 jQuery 编写自定义事件会错过 Blaze 为您提供事件映射的所有功能。

    在此处阅读有关事件地图的更多信息:http://blazejs.org/api/templates.html#Event-Maps

    在此处阅读有关 jQuery 事件的更多信息:https://api.jquery.com/on/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      相关资源
      最近更新 更多