I successfully implemented a form with quill wysiwyg but now I want to create a component to reuse it. This is my working implementation:
<template name="form">
<form>
<div id="toolbar"> ... html with toolbar buttons </div>
<div id="editor"></div>
<input type="submit" value="save"/>
</form>
</template>
Template.form.rendered = function () {
this.quill = new Quill('#editor', {
modules: {
'toolbar': { container: '#toolbar' },
'link-tooltip': true
},
theme: 'snow' }
);
}
Template.form.events({
'submit form': function(e, tmpl) {
e.preventDefault();
var html = tmpl.quill.getHTML();
// code to save the form data
}
This is what I want to make it reusable. My questions are inside the code:
<template name="form">
<form>
{{> editor }}
<input type="submit" value="save"/>
</form>
</template>
<template name="editor">
<div id="toolbar"> ... html with toolbar buttons </div>
<div id="editor"></div>
</template>
Template.editor.rendered = function () {
this.quill = new Quill('#editor', {
modules: {
'toolbar': { container: '#toolbar' },
'link-tooltip': true
},
theme: 'snow' }
);
// How can I pass quill to the parent template?
}
Template.form.events({
'submit form': function(e, tmpl) {
e.preventDefault();
// How can I access quill variable on the nested template, so I can
// call quill.getHTML()?
}
Here's a pattern I use to solve this sort of problem. Define a class called Editor and a template editor. The intention is that the data context inside editor will be an instance of Editor.
function Editor() {
this.quill = null;
}
Template.editor.rendered = function () {
this.data.quill = new Quill(...);
}
<template name="editor">...</template>
Inside form's created callback, create an Editor and store it on the template instance. Then when you call out to the editor template, pass in the Editor instance as the data context.
Template.form.created = function () {
this.editor = new Editor();
}
Template.form.helpers({
editorInstance: function () {
return Template.instance().editor;
}
});
<template name="form">
<form>
{{> editor editorInstance }}
<input type="submit" value="save"/>
</form>
</template>
You can then define methods on the Editor prototype which can be called by the form:
Editor.prototype.getTextAsHTML = function () {
return this.quill && this.quill.getHTML();
}
Template.form.events({
"submit form": function(e, tmpl) {
e.preventDefault();
var html = tmpl.editor.getTextAsHTML();
// ...
}
}
This is a nice way to abstract the details of the editor so that the form doesn't need to know about it. You can reuse the editor and if you ever want to change it, you just have to make sure getTextAsHTML works the same.
Related
//Client side code in client\main.js
Tasks=new Mongo.Collection('tasks');
Template.tasks.helpers({
tasks:function () {
return Tasks.find({},{sort:{createdAt:-1}});
}
});
Template.tasks.events({
"submit .add-task":function (event) {
var name = event.target.name.value;
Meteor.call('addTask',name);
event.target.name.value='';
return false;
},
"click .delete-task":function (event) {
if(confirm('Delete Task?')){
Meteor.call('deleteTask',this._id);
}
return false;
}
});
Meteor.methods({
addTask: function (name) {
if (!Meteor.userId()) {
throw new Meteor.Error('No Access!!');
}
Tasks.insert({
name: name,
createdAt: new Date(),
userId: Meteor.userId()
});
},
deleteTask: function(taskId) {
Tasks.remove(taskId);
}
});
//Server side code in server\main.js
Tasks=new Mongo.Collection('tasks');
Meteor.methods({
addTask: function (name) {
if (!Meteor.userId()) {
throw new Meteor.Error('No Access!!');
}
Tasks.insert({
name: name,
createdAt: new Date(),
userId: Meteor.userId()
});
},
deleteTask: function taskId() {
Tasks.remove(taskId);
}
});
//Html page
<head>
<title>tasklist</title>
</head>
<body>
{{> tasks}}
</body>
<template name="tasks">
{{> loginButtons}}
<h1>Add Task</h1>
{{#if currentUser}}
<form class="add-task">
<label>Task Name</label>
<input type="text" name="name" placeholder="Add Task" />
<input type="submit" value="Submit" />
</form>
{{else}}
<p>Please log in to add tasks</p>
{{/if}}
<hr />
<h3>Tasks</h3>
<ul>
{{#each tasks}}
<li>{{name}}{{#if currentUser}} X{{/if}} </li>
{{/each}}
</ul>
</template>
Please help, in this when i reload page it first add and and shows in the web-page and if i delete the try todelete the added then screen doesnot show even added tasks which are in MongoDB.
And when i do console, there is an empty array of added tasks
If it "blinks" this often means that your Method worked client side but not server side. The insert worked on your Minimongo (client) but not on the real MongoDB (server). So Meteor decide to rollback your insert on Minimongo.
You must have a problem inside your Method server side:
You can't use Meteor.userId() server side in your Methods, you have to use this.userId.
To avoid mistakes, only use this.userId inside the Meteor Methods client or server side.
// Server side
Meteor.methods({
addTask: function (name) {
if (!this.userId) {
throw new Meteor.Error('No Access!!');
}
Tasks.insert({
name: name,
createdAt: new Date(),
userId: this.userId
});
},
deleteTask: function taskId() {
Tasks.remove(taskId);
}
});
In Meteor, you don't have to duplicate your Methods client AND server side.
Methods should always be defined in common code loaded on the client and the server to enable Optimistic UI.
You just have to define your Methods and your collection one time inside a folder loaded on client and server. For exemple you can put your code inside a folder named both/.
I have a search facility in my project and I need to be able to publish results without using autopublish.
html
<template name="search">
<form id="searchform">
<input type="text" id="kategori" placeholder="Sila masukkan maklumat carian."/>
<button>Carian</button>
</form>
<hr/>
<h3>Maklumat</h3>
<ol>
{{#each profil}}
<li>{{jenama}}</li>
{{/each}}
</ol>
</template>
js:
Template.search.events({
"submit #searchform": function (e) {
e.preventDefault();
Session.set("kategori", e.target.text.value);
}
});
Template.search.helpers({
profil: function() {
return Profil.find({
kategori: Session.get('kategori'),
});
}
});
You can simply subscribe to a filtered publication:
client:
Template.search.events({
"submit #searchform": function (e) {
e.preventDefault();
Session.set("kategori", e.target.text.value);
Meteor.subscribe('profiles',Session.get('kategori'));
}
});
server:
Meteor.publish('profiles',function(kategori){
return Profil.find({ kategori: kategori });
});
If you don't have any other subscriptions to the same collection you can also simplify your helper to:
Template.search.helpers({
profil: function() {
return Profil.find();
}
});
Since the set of documents will be defined by your publication.
In practice though you usually use the same search in your helper as you do in the publication just to avoid documents from other publications showing up.
I am having collection issues in my Meteor project. I added the following code to my Resolutions.js file:
Resolutions = new Mongo.Collection('resolutions');
if (Meteor.isClient) {
Template.body.helpers({
resolutions: function() {
Resolutions.find({});
}
});
Template.body.events({
'submit .new-resolution': function(event) {
var title = event.target.title.value;
Resolutions.insert({
title: title,
createdAt: new Date()
});
event.target.title.value = "";
return false;
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
and added the following to my Resolutions.html file:
<head>
<title>Resolutions</title>
</head>
<body>
<div class="container">
<header>
<h1>Monthly Resolutions</h1>
<form class="new-resolution">
<input type="text" name="title" placeholder="A new resolution" />
<input type="submit" value="Submit"/>
</form>
</header>
<ul>
{{#each resolutions}}
{{> resolution}}
{{/each}}
</ul>
</div>
</body>
<template name="resolution">
<li>{{title}}</li>
</template>
After running the app I get zero errors but still the site does not return any of the collection value. I have no clue what is wrong with this project.
Template.body.helpers({
resolutions: function() {
return Resolutions.find({});
}
});
You forgot to use the return keyword.Remember that when creating a helper, you always need to return a value.
I am new to meteor and got stucked and can't understand what am I doing wrong. Enlighten me please.
Here is the HTML file:
<body>
<h1>Do</h1>
{{#if activeTask}}
{{> currentTask}}
{{else}}
{{> newTask }}
{{/if}}
<div>
</div>
</body>
<template name="newTask">
<form>
<label>What<input type="text" name="what" placeholder="gimme an action"/></label>
<input type="submit" value="Go"/>
</form>
<!--
{{> inputAutocomplete settings=settings id="msg" class="input-xlarge" placeholder="action"}}
-->
</template>
<template name="currentTask">
<form>
<label>What<input type="text" name="what" placeholder="gimme an action"/>{{activeTask.what}}</label>
<div>4h 15m</div>
<input type="submit" value="Stop"/>
</form>
</template>
And here is the JavaScript file:
tasks = new Mongo.Collection('tasks');
if (Meteor.isClient) {
Template.body.helpers({
activeTask: function() {
var task = tasks.findOne(
{
endAt: null
},
{
sort: {
startAt: -1
}
}
);
console.log(task);
return task;
}
});
Template.newTask.events({
'submit' : function(event) {
event.preventDefault();
var now = Date.now();
var what = event.target.what.value;
tasks.insert({ what: what, startAt: now, endAt: null });
}
});
}
It successfully adds a new document into the database and logs this in the helper activeTask. One step later it logs no task at all. It has gone. But why?
If you don't have the package autopublish (https://atmospherejs.com/meteor/autopublish) installed, you need to create a publication (client-side) and subscription (server-side):
if (Meteor.isServer) {
Meteor.publish('tasks', function () {
return tasks.find();
});
}
if (Meteor.isClient) {
Meteor.subscribe('tasks');
}
I've also explained working with collections in a recent blog article.
I'm playing around with Meteor and react-meteor. However, I can't seem to grok how the template event-handling works when using react (if it even does).
index.html:
<head>
<title>reactjs</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> FormTest}}
</body>
lib/components/testform.jsx:
var FormTest = ReactMeteor.createClass({
templateName: "FormTest",
render: function() {
return (
<div>
<button className="my-button">My byutton</button>
</div>
);
}
});
index.js:
if (Meteor.isClient) {
Template.FormTest.events({
"click .my-button": function (event, template) {
alert("My button was clicked!");
}
});
}
I get nothing.
Is there something wrong with my code or my approach? If approach, what would be the proper way to handle events?
If you add an event handler here:
<button className="my-button" onClick={this.handleClick}>My button</button>
You can then do this in your testform.jsx file:
handleClick: function(e) {
if (Meteor.isClient) {
e.preventDefault();
console.log("My button was clicked");
}
}
I'm also testing React with Meteor, but this seems to work.