【问题标题】:Meteor -- bind click handler to button inside a conditionalMeteor - 将点击处理程序绑定到条件内的按钮
【发布时间】:2014-09-16 15:00:25
【问题描述】:

我有一个 Meteor 模板,其中包含 2 个可能的 HTML 块,具体取决于条件:already_facebook_authed。正如下面的代码所示,already_facebook_authed 是 Session 变量的结果,并且该 Session 变量是异步设置的。似乎在渲染模板时,Session 变量(因此already_facebook_authed)是错误的,所以当尝试将点击处理程序绑定到#deauth_facebook_button 时,它还不存在,因为它在另一个尚未存在的块中渲染。

如何将点击处理程序绑定到#deauth_facebook_button?当某个 DOM 元素被渲染时,也许会有一些回调,我可以在其中实例化这个点击处理程序?


------------
-- auth.html

<template name="accounts_auth_with_facebook">
  {{#if already_facebook_authed}}
    <div class="col-md-4">
      <button id="deauth_facebook_button" class="btn btn-primary"> Deauth Facebook </button>
    </div>
  {{else}}
    <div class="col-md-4">
      <div id="facebook_button"> Authenticate with FB </div>
    </div>
  {{/if}}
</template>

----------
-- auth.js

Template.accounts_auth_with_facebook.rendered = function () {

  $('#facebook_button').unbind('click.auth').bind('click.auth', function() {
    // some handler code
  });

  $('#deauth_facebook_button').unbind('click.deauth').bind('click.deauth', function() {
    // some other handler code
  });
};

Template.accounts_auth_with_facebook.already_facebook_authed = function() {
  Meteor.call('get_composer_id', function (error, result) {
    if (blah blah blah) {
      Session.set('logged_in_with_facebook', true);
    }
  });
  return Session.get('logged_in_with_facebook');
};

【问题讨论】:

    标签: javascript jquery templates meteor


    【解决方案1】:

    不要使用 jQuery 在 Meteor 模板上设置点击处理程序,使用 Meteor 标准事件机制:

    Template.accounts_auth_with_facebook.events({
      "click #facebook_button":function(event,template){
        // some handler code
      }
      "click #deauth_facebook_button":function(event,template){
        // some other handler code
      }
    });
    

    【讨论】:

    • 谢谢!很快就完成了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    相关资源
    最近更新 更多