如何在模板事件函数中设置上下文数据

Meteor, how to set context data in template event function

本文关键字:设置 上下文 数据 函数 事件      更新时间:2023-09-26

我想在事件处理程序中设置上下文数据,该事件处理程序将新上传的照片插入图像FScollection。我要设置的是照片文件新生成的id。我需要将此id传递给子模板以进行进一步处理。下面是我正在使用的代码:

我应该如何定义我想在事件处理程序中使用的数据?

images.js
Template.Profile.events({
        'change #uploadBtn': function(event, template) {
            var name = $("#uploadBtn").val();
            $("#uploadFile").val(name);
            FS.Utility.eachFile(event, function(file) {
                Images.insert(file, function (err, fileObj) {               
                    if (err){
                        // handle error
                    } 
                    else {
//here I want to set fileObj._id as data for further usage.
                    }
                });
            });
        }
    });
    Template.imageView.helpers({
        images: function () {          
            return Images.findOne({_id: this.imageId}); 
        }
    });
Template.imageView.events({
            'click #deleteBtn': function (event) {
                this.remove();
            }
        });

模板文件

  images.html
    <template name="Profile">
      <input id="uploadFile" placeholder="Choose File" disabled="disabled" style="cursor: auto; background-color: rgb(235, 235, 228); "/>
      <div class="fileUpload btn btn-primary">
        <span>Upload</span>
        <input id="uploadBtn" type="file" name="…" class="upload">
      </div>
      {{> imageView}}
    </template>
    <template name="imageView">
      <div class="imageView">
        {{#if images}}
          <div style="width: 120px;height: 120px;margin-bottom: 30px;">
            <div style="float: middle;">
              {{#with images}}
              <button id="deleteBtn" type="button" class="btn btn-primary" >Delete</button>
              {{/with}}
            </div>
            <a href="{{images.url}}" target="_blank" >
              <img src="{{images.url}}" alt="" class="thumbnail" style="width: 96px; height: 96px;"/>
            </a>        
          </div>
        {{/if}}
      </div>
    </template>

您有几个选择。

  1. 在引用它的对象中包含图像的_id
  2. 在图像中包含对象的_id,如parentId或类似的

对于第一种情况,在Image.insert的回调中使用图像的_id,然后在父对象(这可能是用户吗?)上执行.update()以包含对图像的引用。如果你允许使用多个图像,那么你可能需要用这些_id来更新一个数组。

在第二种情况下,你可以用你需要的parentId来更新你刚刚插入回调的对象。

然后你只需要在你的查询中包含相应的子句,依赖的图像,由于反应性,它会自动更新。