【问题标题】:Meteor: how to retrieve "{{this}}-value" with a template eventMeteor:如何使用模板事件检索“{{this}}-value”
【发布时间】:2016-04-02 14:29:09
【问题描述】:

注意:完整代码可以在这里找到:

https://github.com/Julian-Th/crowducate-platform/tree/feature/courseEditRights

问题:我无法通过事件检索 {{this}} 值。 Console.log() 正在打印 0。

我的 HTML:

<!-- Modal to control who can collaborate on a course-->

<template name="modalAddCollaborators">
  <div id="modalAddCollaborators" class="modal fade" role="dialog">
    <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Manage Your Collaborators</h4>
      </div>
      <div class="modal-body">
        <form class="form" role="form">
          <ul class="list-group">
            {{#each  addedCollaborators}}
              {{#each canEditCourse}}
                 <li class="list-group-item js-listed-collaborator">{{this}}<a title="Remove Collaborator" id="remove-collaborator" class="btn btn-danger pull-right" href="#"><i class="fa fa-trash"></i></a></li>
             {{/each}}
            {{/each}}
          </ul>
          <div class="form-group">
            <input class="form-control typeahead" type="text" id="collaboratorName" placeholder="add a collaborator  ..." data-source="courses" autocomplete="off" spellcheck="off">
            <button type="button" id="js-addCollaborator" class="btn btn-success">Add</button>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
</template>

我的 JS:

Template.modalAddCollaborators.rendered = function() {
    // initializes all typeahead instances
    Meteor.typeahead.inject();
};

Template.modalAddCollaborators.courses = function(){
    return Courses.find().fetch().map(function(it){ return it.author; });
 //return users.find().fetch().map(function(it){ return it.username; });
};

Template.modalAddCollaborators.helpers({
    'addedCollaborators': function () {
        return Courses.find().fetch();
    }
});

Template.modalAddCollaborators.events({
    'click #js-addCollaborator' : function (event) {
        var collaboratorName = $('#collaboratorName').val(); // 
        Courses.update(
           {_id: this._id},
           {$addToSet: {canEditCourse: collaboratorName}}
        );
        $('#collaboratorName').val("");
    },
    'click #remove-collaborator': function (event) {
        var listedCollaborator = $('.js-listed-collaborator').val();
        console.log(listedCollaborator);
        Courses.update(
            {_id: this._id }, 
            {$pull: {canEditCourse: listedCollaborator}}
        );
    }
});

我的 MongoDB JSON:

{
    "_id" : "j7A3tFdFBn5ECQGwe",
    "title" : "Beatles",
    "coverImageId" : "RERiadyMx8j8C9QQi",
    "author" : "John",
    "keywords" : [ 
        "Paul"
    ],
    "published" : "true",
    "about" : "Testing the Course",
    "canEditCourse" : [ 
        "uo8SMdNroPGnxMoRg", 
        "FLhFJEczF4ak7CxqN", 
        "lkahdakjshdal", 
        "asödjaöslkdjalsöSA"
    ],
    "createdById" : "uo8SMdNroPGnxMoRg",
    "dateCreated" : ISODate("2015-12-28T16:30:34.714Z")
}

从 JS 文件中可以看出,我的最终目标是从数组中删除被点击的用户。

【问题讨论】:

    标签: javascript mongodb templates meteor


    【解决方案1】:

    要在子链接点击事件中获取li项的文本,结合使用.parent().text()(因为你可以' t 在列表项上使用 .val()):

    'click #remove-collaborator': function (event) {
        console.log(event.target);
        var listedCollaborator = $(event.currentTarget).parent().text();
        console.log(listedCollaborator);
        console.log(JSON.stringify(Template.parentData(0)));
        Courses.update(
            { 
                _id: Template.parentData(0)._id, /* or _id: Template.currentData()._id, */
                canEditCourse: listedCollaborator 
            }, 
            { $pull: { canEditCourse: listedCollaborator } }
        );
    }
    

    请注意,您可以通过 event.currentTarget 在事件冒泡阶段使用当前 DOM 元素来引用启动事件的元素。由于元素是锚标记,因此您将获得 li 项目为 它的 .parent(),然后通过 .text() 获得它的值。

    至于更新,使用Template.parentData()获取父_id。在方法中指定参数0,表示要查看的当前数据上下文级别。

    例如,Template.parentData(0) 等价于 Template.currentData()Template.parentData(2) 相当于模板中的{{../..}}

    【讨论】:

    • 发生了一些非常奇怪的事情:console.log(listedCollaborator) 打印了一些值,而其他的只是空的(甚至不是 0)。就我而言,控制台中通常会显示四个中的两个。然而,它们都还在 canEditCourse 数组中——所以它们都没有被删除。我将 JSON 添加到问题中。希望它有所帮助。
    • console.log(event.target);console.log($(event.target).parent()); 打印什么?
    • $(event.currentTarget).parent().text();修复。 :) 但是,Courses.update 不会删除用户。
    • 非常感谢。 Template.parentData(0)._id 有效 :) console.log(JSON.stringify(Template.parentData(1))) 打印“无法读取属性 '_id' of null; 而 this._id 只是“未定义”。你知道为什么吗?无论如何,我接受了你的回答。你是我的英雄!连续两次帮助我。
    • @AmirRahbaran 不错,之前犯了一个错误;将{{each}} 块的嵌套作为当前数据上下文级别的基础。你是对的Template.parentData(0)._id 应该带来所需的上下文;我已经更新了我的答案以反映这一点。谢谢!
    【解决方案2】:

    由于您已将事件处理程序附加到modalAddCollaborators 模板this 将是该模板的数据上下文,它什么都不是。

    只需在您想要捕捉事件的级别设置一个嵌套模板。

    此外,使用此模式,您可以直接识别协作者的_id,它将是this。然而,_id 课程来自parent 模板的上下文。 (但我不确定课程级别的数据上下文是否高 1 级或 2 级)。

    html:

    {{#each canEditCourse}}
      {{> nestedTemplate }}
    {{/each}}
    
    <template name="nestedTemplate">
      <li class="list-group-item js-listed-collaborator">
        {{this}}<a title="Remove Collaborator" id="remove-collaborator" class="btn btn-danger pull-right" href="#"><i class="fa fa-trash"></i></a>
      </li>
    </template>
    

    js:

    Template.nestedTemplate.events({
      'click #remove-collaborator': function (event) {
        Courses.update({_id: Template.parentData()._id },{$pull: {canEditCourse: this}});
      }
    });
    

    【讨论】:

    • 结果相同:0 :(
    • 哦,我明白了,canEditCourse 是一个字符串数组,而不是对象。在您的数据上下文中没有this._id,只有this(没有键)。我将更改代码。
    • 现在我得到了这个:meteor.js:864: Exception while simulating the effect of invoking '/courses/update' 错误:documentMatches 需要一个文档(…)错误:documentMatches 需要一个文档
    猜你喜欢
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 2014-11-22
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多