【问题标题】:How to instantiate event listeners on new template rendered with blaze?如何在 blaze 渲染的新模板上实例化事件侦听器?
【发布时间】:2015-06-12 00:54:17
【问题描述】:

我有一个由 Blaze 呈现的模板,因为我创建了一个登录页面,然后在用户单击注册按钮时将其删除,然后将其带到 Blaze 呈现的另一个模板。

HTML 非常空白,只有一个 div 用于模板

<head>
  <title>Perform</title>
</head>

<body>
<div id="template">
</div>

</body>

这是加载的第一个虚拟模板。

<template name="first">
    <button id="first_button">Click to jump to the next template</button>
</template>

以及加载的第二个(虚拟)模板

<template name="second">
    <button id="second_button">This button is not wired to an event</button>
</template>

我已将所有 Javascript 加载到客户端上运行的一个文件中:

var currentView;
var templateContainer;
$(document).ready(function() {

    templateContainer = document.getElementById('template');

    // This renders the first template. All events are currently working
    currentView = Blaze.render(Template.first, templateContainer);
});

Template.first.onDestroyed(function() {
    // This console.log is firing
    console.log("Destroyed first template");
});

Template.first.events({
    'click #first_button': function () {
    // Remove the first template with Blaze
    Blaze.remove(currentView);

    // Render the second template
    currentView = Blaze.render(Template.second, templateContainer);
    }
});


Template.second.onCreated(function() {
    // This console.log is firing when the 'second' template is created
    console.log("Hello! I've been created");
});
// The second template is actually a form I'd like to submit. Form omitted for brevity
Template.second.events({
    'submit #second_button': function(e, t) {
        // This console log is not firing.
        console.log("Register clicked");

    }
});

有人知道我需要做什么才能触发“第二个”模板的事件吗?它只是不起作用,现在有点令人沮丧。

提前感谢您的帮助。

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    好吧,我是个彻头彻尾的白痴,最终自己解决了这个问题。

    第二个模板的点击事件在测试和调试后实际上可以工作,但是提交事件将不起作用。这是两个完全不同的事情,我只是一个没有澄清这一点的白痴。对于之前看到此内容并感到困惑的人,我们深表歉意。

    代替:

    Template.second.events({
    'submit #second_button': function(e, t) {
        // This console log is not firing.
        console.log("Register clicked");
        }
    });
    

    我改成:

    Template.second.events({
    'submit #second_button': function(e, t) {
        // This console log is now firing
        console.log("Register clicked");
        e.preventDefault()
        return false;
    
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-20
      • 2017-03-13
      • 2011-10-14
      • 2017-08-19
      • 1970-01-01
      • 2017-07-18
      • 2013-07-25
      • 1970-01-01
      相关资源
      最近更新 更多