【发布时间】:2014-01-16 09:31:42
【问题描述】:
我是 Meteor 的新手,我正在构建一个简单的应用程序来学习该框架。我正在构建的应用程序可让您在小猫的图像上放置文字。
期望的行为是这样的:
用户点击小猫的任意位置,会出现一个 contenteditable 元素,让用户输入文本。在元素外部单击可保存元素,并保持原位。
我遇到的问题:
如果我使用该应用程序打开了两个浏览器窗口,并且我在一个窗口中单击了一只小猫,则两个窗口中都会出现一个空白字段。理想情况下,空白字段只会出现在我单击的窗口上。一旦保存了一个单词,那么 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>
【问题讨论】:
标签: javascript collections meteor