我刚接触到Meteor,并开发了一个简单的应用程序来学习这个框架。我正在开发的应用程序让我们把文字放在一只小猫的图片上。
所需的行为如下:
用户单击猫上的任何位置,就会出现一个允许用户输入文本的可内容元素。单击元素的外部保存元素,它将保持不变。
我遇到的问题:
如果我打开了两个浏览器窗口,并且在一个窗口中单击一只小猫,则两个窗口中都会出现一个空字段。理想情况下,空字段只出现在我单击的窗口上。一旦保存了一个单词,那么in在两个窗口中都是可见的。
我的问题:
是否有一种方法只将文档insert到客户端的集合中,然后使用upsert将文档添加到服务器端集合?
,这是我尝试过的:
我创建了一个仅存在于客户端的存根方法,用于插入文档。这方面的问题是,当我单击图像时,一个空字段出现在一瞬间,然后再次消失。
,这是代码:
image-tags.js
if (Meteor.isClient) {
var isEditing;
Template.image.image_source = function () {
return "http://placekitten.com/g/800/600";
};
Template.tag.rendered = function(){
var tag = this.find('.tag');
if (isEditing && !tag.innerText) {
tag.focus();
}
}
Template.image.events({
'click img' : function (e) {
if (isEditing) {
isEditing = false;
} else {
isEditing = true;
var mouseX = e.offsetX;
var mouseY = e.offsetY;
// Tags.insert({x:mouseX, y:mouseY});
// Insert tag on the client-side only.
// Upsert later when the field is not empty.
Meteor.call('insertTag', {x:mouseX, y:mouseY});
}
},
'click .tag' : function (e) {
isEditing = true;
},
'blur .tag' : function (e) {
var currentTagId = this._id;
var text = e.target.innerText;
if(text) {
Tags.upsert(currentTagId, {$set: {name: text}});
} else {
Tags.remove(currentTagId);
}
}
});
Template.image.helpers({
tags: function() {
return Tags.find();
}
});
// Define methods for the collections
Meteor.methods({
insertTag: function(attr) {
Tags.insert({x:attr.x, y:attr.y});
}
});
}
// Collections
Tags = new Meteor.Collection('tags');image-tags.html
<head>
<title>Image Tagger</title>
</head>
<body>
{{> image}}
</body>
<template name="image">
<figure>
<img src="{{image_source}}" />
<figcaption class="tags">
{{#each tags}}
{{> tag}}
{{/each}}
</figcaption>
</figure>
</template>
<template name="tag">
<div class="tag" contenteditable style="left: {{x}}px; top: {{y}}px;">
{{name}}
</div>
</template>发布于 2013-12-29 09:42:31
您应该将临时标记(可能还有您的isEditing var)存储在Session中
Session.set("isEditing", true);
Session.set("newTag", {x:mouseX, y:mouseY});在初始化集合时,还可以通过传递null而不是集合名称来创建本地集合。然而,Session应该为您所做的工作而工作。查看领导板以获得一个示例。
编辑:
<figcaption class="tags">
{{#each tags}}
{{> tag}}
{{/each}}
{{#with newTag}}
{{> tag}}
{{/with}}
</figcaption>
Template.image.newTag = function() {
return Session.get("newTag");
}发布于 2014-01-08 16:41:34
如果仅在客户端创建集合,则如果断开连接,可能会出现问题:新文档不会存储在服务器上。
在我看来,最好的方法是设置一个属性“已发布”、“编辑”或“状态”(带有值已发布/ eiditing /.)在你的文件里。那么您的发布方法应该返回:
当用户创建文档时,它存储在服务器上,但具有编辑状态。然后,当您保存时,您可以决定发布它,然后所有其他用户都将在他们的订阅中接收文档。
希望替代的解决方案能帮助你。
https://stackoverflow.com/questions/20823587
复制相似问题