【问题标题】:How to pass a function to a Meteor template?如何将函数传递给 Meteor 模板?
【发布时间】:2014-09-30 15:19:58
【问题描述】:

我想插入一个 Meteor 模板(一个简单的登录表单),但我想控制表单提交后会发生什么。理想情况下,我希望能够将函数 afterLogin() 传递给模板。但我很不确定如何做到这一点,以及这是否可能。

我最近看到了一个有趣的包viewmodel,但我不确定它的相关性如何。但在这种情况下,目标基本上是用不同的视图模型渲染视图。

有什么想法吗?我目前正在使用会话变量,然后在登录后,我检查该会话变量以运行正确的功能,但这很丑陋且不易使用。有什么想法吗?

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    这就是我的做法:

    我假设您的登录表单是从父模板中调用的,使用属性语法将自定义助手的值传递给登录表单的数据上下文。

    <template name="parent">
      {{> loginForm options=loginFormOptions}}
    </template>
    

    助手返回一个封装函数的对象,调用者负责将该函数设置为他们想要的任何东西。

    Template.parent.helpers({
      loginFormOptions:function(){
        return {
          afterLogin:function(){
            // we assert that the context is correct :
            // this will print Template.loginForm
            console.log(this.view.name);
          }
        };
      }
    });
    

    您的登录表单代码作为一个库,可以从其数据上下文中读取调用者模板传递的函数,然后使用正确的this 上下文调用该函数。

    Template.loginForm.events({
      "submit":function(event,template){
        // ...
        Meteor.loginWithPassword(...,function(error){
          if(error){
            console.log(error);
            return;
          }
          // guard against the existence of the custom afterLogin function
          if(template.data.options && template.data.options.afterLogin){
            // execute the custom function with proper context
            template.data.options.afterLogin.call(template);
          }
        });
      }
    });
    

    【讨论】:

    • 就是这样。我想您必须传递包装在对象中的函数。
    【解决方案2】:

    首先,我会使用 Iron Router 来浏览我的应用程序的不同视图,您可以在此处获取: https://github.com/EventedMind/iron-router

    meteor add iron:route
    

    然后,检查http://docs.meteor.com/#template_events。我会使用类似的东西:

    Template.loginFormTemplate.events({
      'click .loginButton': function() {
        //... if success login ...
        Router.go('nextScreen');
      }
    });
    

    [更新 1]

    恐怕在 Meteor 架构的意义上,试图将函数传递给 Route 是一种丑陋的方法。

    您可以尝试定义一些全局变量,该变量负责跨路由侦听和转发触发事件

    var eventHelper = (function () {
        var self = _.extend({
            afterLogin: function () {
                self.trigger('forwardedEvent');
            }}, Backbone.Events);
    
        return self;
    })();
    
    
    Route1.events({
        'click': function () {
            //... Let's call after login
            eventHelper.afterLogin();
        }
    });
    
    eventHelper.on('forwardedEvent',function() {
       // ... 
    });
    

    【讨论】:

    • 我用的是铁路由器。问题是我想调用传递给模板的任意函数,而不是Router.go('nextScreen')...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2015-09-02
    • 2013-09-02
    • 2014-03-11
    • 2016-04-17
    • 1970-01-01
    • 2017-12-25
    相关资源
    最近更新 更多