【问题标题】:Meteor: No context for #each loop event handlersMeteor:#each 循环事件处理程序没有上下文
【发布时间】:2016-06-28 11:53:55
【问题描述】:

我正在使用带有非托管本地集合的#each 循环来为表单生成一系列输入字段。但是,当我尝试在事件处理程序中使用 this._id 时,它是未定义的。实际上,传递给事件处理程序的上下文是针对窗口的。非常感谢任何帮助找出问题所在以及我应该如何在我的事件处理程序中获得正确的上下文作为this

代码是:

<h4 class="page-header">Children on this account</h4> 
{{#each children}}
<div id={{_id}} class="form-group col-md-12 child-form-instance">
    <div class="form-group col-sm-5 col-xs-12">
        <input type="text" name="childFirstName" class="form-control" placeholder="Child's First Name">
    </div>

    <div class="form-group col-sm-5 col-xs-10">
        <input type="text" name="childLastName" class="form-control" placeholder="Child's Last Name" value="{{_id}}">
    </div>
    <div class="form-group col-xs-2">
        <button type="button" class="btn btn-danger remove-child" aria-label="remove child">
            <span class="glyphicon glyphicon-trash"></span>
        </button>
    </div>
</div>
{{/each}}
<div class="form-group">
    <input type="button" id="addChild" class="btn btn-success" value="Add child">
</div>

和js:

var children = new Mongo.Collection(null);

Template.signup.onRendered( () => {
  Modules.client.signupValidateSubmit({
    form: "#signup",
    template: Template.instance()
  });
    children.remove({});
    children.insert({});  //create one empty child

});

Template.signup.events({
    'submit form': ( event ) => event.preventDefault(),
    'click #addChild': () => {
        children.insert({});
        console.log(children.find().fetch());
    },
    'click .remove-child': () => {
        console.log(this);
    }
});

Template.signup.helpers({
    children () {
        return children.find();    
    }
});

addChild 按钮一切正常,_ids 已在 DOM 中正确分配,但 remove-child 类正在记录 window 上下文。

【问题讨论】:

  • 好吧,你使用的箭头函数将在词法上绑定this。结果,您得到了错误的上下文。
  • 是的,这就是整个问题。 function() 修复它。看来我应该更多地阅读 ES2015,而不仅仅是照搬我看到的一些约定。感谢马蒂亚斯的帮助!

标签: meteor spacebars


【解决方案1】:

您正在使用ES6 arrow functions,它将在词法上将this 与父作用域绑定。因此,您无法获得children 的范围。

为了解决问题,只需将模板事件更改为:

Template.signup.events({
    // ...
    'click .remove-child': function (event, template) {
        console.log(this);
    }
    // ...
});

【讨论】:

    猜你喜欢
    • 2015-04-05
    • 2017-09-09
    • 2012-01-18
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    相关资源
    最近更新 更多