【问题标题】:Meteor, how to set context data in template event functionMeteor,如何在模板事件函数中设置上下文数据
【发布时间】:2015-10-07 18:32:18
【问题描述】:

我想在将新上传的照片插入图像 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>

【问题讨论】:

    标签: javascript meteor meteorite


    【解决方案1】:

    你有几个选择。

    1. 在引用它的对象中包含图像的 _id
    2. 在图像本身中包含对象的 _id 作为 parentId 或类似

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

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

    然后,您只需在查询中包含相关图像的适当子句,并且由于反应性,它会自动更新。

    【讨论】:

    • ps。这假设您要保持图像和父对象之间的关系。如果你不这样做,那么你可以在存储图像 _id 的同一个文件中定义一个闭包。
    • 是否可以更新模板数据上下文,看起来更直接。
    • 可以使用闭包,但不会跨会话持续存在。如果上传要永久附加到相关对象,则需要更新子对象或父对象。
    猜你喜欢
    • 2014-12-09
    • 2015-08-11
    • 2013-12-26
    • 2015-01-02
    • 1970-01-01
    • 2015-03-07
    • 2018-08-26
    • 2016-07-11
    • 1970-01-01
    相关资源
    最近更新 更多