我是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>
您应该将临时标记(可能还有您的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");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句