Can Meteor handle nested views? - meteor

I'm learning meteor, and finding all kinds of difficulties dealing with nested subviews. Since the application I want to write is full of them... that looks like a difficulty. I found this on github, as a readme for a Meteor project to try and deal with this problem.
"I've been playing around with Meteor for a couple weeks. The ease of setup and the powerful reactivity makes this something I want to stick with. I was however frustrated by the difficulty of programmatically configuring, instantiating, destroying and nesting subviews."
Is this an issue that can be handled in Meteor (without adding a lot of complicated work arounds) or should I look for a different platform ?

I love nesting templates. I get reliable results. I now program off a library of both templates and helper functions (usually for form elements) that compose html for me. HTML is a byproduct, and the files we call .html are really a javascript DSL.
There are many S.O. issues raised about insertions into sorted lists giving people problems. I haven't had time to look.
My rule of thumb: Meteor is (well) designed from the beginning to do this easily and reliably.
So far the harder thing to solve was when I added an accordion from foundation, and a refresh of the document led to its initial state (being all closed, or one open). I had to put code in that saved the current section, and code to re-assert that in the rendered callback for the template that used it.
Why not write a prototype of the nesting with just a field or two in places, and find what bothers you?
Here is a sample chain. You see all the nested templates. This template itself is running within multiple.
First template: called 'layout', suggested by iron router. Has basic page and menu. Main body is a yield, set by router. On a sample page, a route calls template 'availability'
<template name='availability'>
{{#each myAgents}}
<form class="custom" id="Agent_{{_id}}" action="">
<div id='availability' class="section-container accordion" data-section="accordion">
<section id="services">
<p class="title" data-section-title><a href="#">
Your Info
</a></p>
<div class="content" data-section-content>
{{>services}}
</div>
</section>
<section id="skills">
<p class="title" data-section-title><a href="#">
Skills
</a></p>
<div class="content" data-section-content>
{{>skills}}
</div>
</section>
<section id="sureties">
<p class="title" data-section-title><a href="#">
Sureties
</a></p>
<div class="content" data-section-content>
{{>sureties}}
</div>
</section>
<section id="time">
<p class="title" data-section-title><a href="#">
Time Available
</a></p>
<div class="content" data-section-content>
{{>time}}
</div>
</section>
<section id="schedule1">
<p class="title" data-section-title><a href="#">
Schedule 1
</a></p>
<div class="content" data-section-content>
{{>schedule}}
</div>
</section>
<section id="schedule2">
<p class="title" data-section-title><a href="#">
Schedule 2
</a></p>
<div class="content" data-section-content>
{{>schedule}}
</div>
</section>
<section id="distance">
<p class="title" data-section-title><a href="#">
Distance
</a></p>
<div class="content" data-section-content>
{{>distance}}
</div>
</section>
</div>
</form>
{{/each}}
</template>
sample further nest:
<template name='services'>
{{label_text fname='name' title='Agent Name' placeholder='Formal Name' collection='agent' passthrough='autofocus=autofocus ' }}
{{label_text fname='agentInCharge' title='Agent In Charge' placeholder='Owner' collection='agent' }}
{{label_text fname='phone' title='Phone Number(s)' placeholder='Include Area Code'collection='agent' }}
{{>gps }}
<h4>Not shared:</h4>
{{label_text fname='email' title='Email:' placeholder='you remain anonymous' collection='agent' }}
</template>
and label_text is a helper, learned from the https://github.com/mcrider/azimuth project:
generateField = (options) ->
options.hash.uniqueId = options.hash.fieldName + "_" + Math.random().toString(36).substring(7) if options.hash.template is "wysiwyg"
options.hash.id = options.hash.id or #_id
options.hash.value = options.hash.value or this[options.hash.fname]
# allow for simple params as default
options.hash.title = options.hash.title or options.hash.fname
options.hash.template = options.hash.template or "label_text"
options.hash.placeholder = options.hash.placeholder or options.hash.title
# compatible with old
options.hash.fieldName = options.hash.fieldname or options.hash.fname
options.hash.label = options.hash.label or options.hash.title
# FIXME: Return error if type not valid template
new Handlebars.SafeString(Template[options.hash.template](options.hash))
Handlebars.registerHelper "label_text", (options) ->
options.hash.collection = options.hash.collection or 'generic'
generateField.call this, options

I am fairly new to Meteor, but I found out really soon that I wanted nested views (aka dynamic includes or sub-templates). I'm not sure whether this is what you mean, but here is my solution.
I created the following handlebars helper, that can be used to create sub-templates:
Handlebars.registerHelper('subTemplate', function(container, property, context, options) {
if (container && container.hasOwnProperty(property)) {
var subTemplate = container[property];
if (typeof subTemplate === 'function') {
return new Handlebars.SafeString(subTemplate(context || this));
}
else if (typeof subTemplate === 'string') {
return new Handlebars.SafeString(Template[subTemplate](context || this));
}
}
});
It can be used inside something I call a generic template. For example to create a list:
<template name="item_list">
<ul class="items-list">
{{#each items}}
<li class="listview-item">
{{subTemplate .. 'listItem' this}}
</li>
{{/each}}
</ul>
</template>
Now invoking this generic template requires that a 'listItem' property is present within its context. This can be either a string with the name of the sub-template, or the inline definition of a sub-template. The example below shows both options:
<template name="my_list">
{{! First option, referring to the sub-template by name:}}
<div>
{{#with listData listItem="my_list_item"}}
{{> item_list}}
{{/with}}
</div>
{{! Second option, inlining the sub-template:}}
<div>
{{#with listData}}
{{#assignPartial 'listItem'}}
<span>{{name}}</span>
{{/assignPartial}}
{{> item_list}}
{{/with}}
</div>
</template>
<template name="my_list_item">
<span>{{name}}</span>
</template>
Template.my_list.listData = function() {
return {
items: collections.people.find()
};
};
The second option requires an extra handlebars helper.
Handlebars.registerHelper('assignPartial', function(prop, options) {
this[prop] = options.fn;
return '';
});
I made more of these kinds of useful helpers, at some point I will probably share them on GitHub.

Related

Updating parent of recursive component in Vue

I've made a menu showing systems and their subsystems (can in theory be indefinitely) using a recursive component. A user can both add and delete systems, and the menu should therefore update accordingly.
The menu is constructed using a "tree"-object. This tree is therefore updated when a new system is added, or one deleted. But, I now have a problem; even though the new child component is added when the tree is rerendered, the classes of it's parent-component doesn't update. It is necessary to update this because it defines the menu-element to having children/subsystems, and therefore showing them.
Therefore, when adding a new subsystem, this is presented to the user:
<div class="">
<a href="#/Admin/364" class="item">
<i class=""></i>Testname
<div class=""></div>
</a>
</div>
Instead of this:
<div class="menu transition visible" style="display: block !important;">
<a href="#/Admin/364" class="item">
<i class=""></i>Testname
<div class=""></div>
</a>
</div>
It works fine adding a subsystem to a system which already have subsystems (since the menu-class is already present), but not when a subsystem is added to one without subsystems. In that case, the menu ends up looking like this:
The "opposite" problem also occurs on deletion, since the parent still has the menu-class:
Here's the code for the recursive component:
<template>
<router-link :to="{ name: 'Admin', params: { systemId: id } }" class="item" >
<i :class="{ dropdown: hasChildren, icon: hasChildren }"></i>{{name}}
<div :class="{ menu: hasChildren }">
<systems-menu-sub-menu v-for="child in children" :children="child.children" :name="child.name" :id="child.id" :key="child.id"/>
</div>
</router-link>
</template>
<script type = "text/javascript" >
export default {
props: ['name', 'children', 'id'],
name: 'SystemsMenuSubMenu',
data () {
return {
hasChildren: (this.children.length > 0)
}
}
}
</script>
I'm guessing this has to do with Vue trying to be efficient, and therefore not rerendering everything. Is there therefore any way to force a rerender, or is there any other workaround?
EDIT: JSFiddle https://jsfiddle.net/f6s5qzba/

Use a helper to set a css class

I need to make reactive a class inside a const (exported from a module).
export const messageControls = '
<div id="controls"">
<i id="idcont" class="{{starred}}"></i>
</div>
'
This class belongs to an HTML block who's inserted as innerHTML of a createElement.
var newElement = document.createElement('div');
newElement.id = i._id;
newElement.className = "single_message";
newElement.innerHTML = messageControls;
document.getElementById('conversation_details').appendChild(newElement);
The {{helper}} below is not rendering anything :
starred: function () {
return 'bob';
},
<i id="idcont" class="{{starred}}"></i> gives {{starred}} in plain text
<i id="idcont" class=" ' + {{starred}} + ' "></i> breaks all
Any idea?
Update - full Blaze template as requested
<template name="inbox">
<div class="searchmessages">
<input type="text" name="searchmessages" id="searchmessages" placeholder="  any word / any date">
</div>
<div class="row">
<div class="col-xs-4 l-O list_messages">
<div id="gridreceived" class="gridmessages">
{{#each incoming_all}}
<div id="{{_id}}" class="item {{readornot}}">
<div class="item-content">
<div class="task_inlist">
<div class="task_from">
{{{from}}}
</div>
<div class="task_date">
{{initialdate}}
</div>
<div class="task_subject">
{{{subject}}}
</div>
<div class="task_content">
{{{htmlbody}}}
</div>
</div>
</div>
</div>
{{/each}}
</div>
<div class="grid_nomatch">{{grid_noresult}}</div>
</div>
<div id="conversation_details" class="col-xs-8" media="print">
<!--
here are each selected message details
-->
</div>
</div>
</template>
You're trying to inject spacebars template markup directly into the DOM but meteor-blaze wants to use spacebars to build the DOM. It doesn't watch the DOM for arbitrary changes and then make template substitutions inside of it!
You can instead use Meteor's reactivity to automatically insert new items into the DOM for you based on changes to the underlying data. In your case it looks like you're trying to show the details of a message that's been clicked on. You probably have a template event handler already to catch the click. In that template handler you can set a Session variable which indicates which message is currently selected and then use that Session variable inside the helper that renders the message details.
For example:
<template name="inbox">
<div class="searchmessages">
<input type="text" name="searchmessages" id="searchmessages" placeholder="  any word / any date">
</div>
<div class="row">
<div class="col-xs-4 l-O list_messages">
<div id="gridreceived" class="gridmessages">
{{#each incoming_all}}
<div id="{{_id}}" class="item {{readornot}}">
// render summary of each message
</div>
{{/each}}
</div>
<div class="grid_nomatch">{{grid_noresult}}</div>
{{#with selectedMessage}}
<div id="conversation_details" class="col-xs-8" media="print">
// render selected message details
</div>
{{/with}}
</div>
</template>
Your js:
Template.inbox.events({
'click .item'(ev) {
Session.set('selectedMessageId',this._id);
}
});
Template.inbox.helpers({
selectedMessage() {
return Messages.findOne(Session.get('selectedMessageId'));
}
});
Now to your follow-up question about how to reactively style an element. Let's say your message* object has aisStarredboolean key. In the message detail section we've set the data context using{{#with currentMessage}}` so any key of the current message can be used directly in our spacebars template. Where you are displaying the message details you can do:
<div id="controls"">
<i id="idcont" class="{{#if isStarred}}starred{{/if}}"></i>
</div>
Depending on whether or not the message is starred this will render as class="" or class="starred".

Inject data into scope without <template>

I would like to get rid of two lines in the html used in a vue 2.x application. The lines with <template scope="props"> and the corresponding </template> should not be necessary.
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<p>{{ message }}</p>
<my-component>
<template scope="props">
<p>{{props.test}}</p>
</template>
</my-component>
</div>
I would rather define my own component attribute to define the scope name
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<p>{{ message }}</p>
<my-component with="props">
<p>{{props.test}}</p>
</my-component>
</div>
So instead of exposing the writer of the HTML to the concepts of templates and scopes we would do that inside my-component.
Does anybody know whether the vue templating mechanism is open for extension inside components like this ?
The benefit of having component is that it can be re-used at multiple places. so idea is to define template at one place and you can use it at multiple places.
the example you have written, you will be able to re-use it at again. template of component is generally not defined inside component, it will be separate and than that component can be used at multiple places.
See one sample below:
<div id="app">
<template id="item-edit">
<li>
<span v-show="!inEdit">{{item.name}}</span>
<input v-show="inEdit" type="text" v-model="item.name" />
{{inEdit ? 'save' : 'edit'}}
</li>
</template>
<ul>
<item-edit v-for="item in items" :item="item"></item-edit>
</ul>
</div>
Complete fiddle: http://jsfiddle.net/corh2tqo/

SASS / HandlebarsJS conflicts?

Background: For a project, I am trying to use SASS and Handlebars to create a vote counter that displays a stored value from my database and updates when a user presses the up or down vote buttons.
Are there any known interactions/conflicts that would causes SASS styling to not be applied when used with Handlebars or vice-versa?
For reference, here is the code I have in my HTML that I am working with.
<div id='voteWrapper'>
<script id='voteTile' type="text/x-handlebars-template">
{{#each proTipVote}}
<div class="vote circle">
<div class="increment up" data-id={{_id}}></div>
<div class="increment down" data-id={{_id}}></div>
<div class="count" data-id={{_id}}>{{tipScore}}</div>
</div>
{{/each}}
</script>
</div>

Meteor js not responding

I have been working with meteor.js and have been practicing using examples from getting started with meteor.js Javascript framework. The book is 2 years old and I have been running across some snags. For instance the book tells you to use var to define a variable, but after searching on stack I read that you didn't have to use it and now it works. I'm new so I write programs, run them, debug them and start from scratch to help me learn. For some reason this program that I have done 4 times before today is not running and I cant figure out why.
I keep getting this message :
While building the application:
LendLib.html:37: Expected "template" end tag
...  </div>
after inputting the following code:
<head>
<title>LendLib</title>
</head>
<body>
{{> hello}}
<div id="categories-container">
{{> categories}}
</div>
</body>
<template name="hello">
<h1>Lending Library</h1>{{greeting}}
<input type="button" value="Click" />
<template name="categories">
<div class="title">my stuff</div>
<div id="categories">{{#each lists}}
<div class="category">{{Category}}</div>{{/each}} </div>
</template>
</template>
any advice will be appreciated
dont define templates inside another template.
try like this.
<template name="hello">
<h1>Lending Library</h1>
{{greeting}}
<input type="button" value="Click" />
</template>
<template name="categories">
<div class="title">my stuff</div>
<div id="categories">
{{#each lists}}
<div class="category">
{{Category}}
</div>
{{/each}} 
</div>
</template>
Like pahan said, you cannot define a template within another template. They each have to be separate and un-nested. You CAN, however, call a template from within another template.
<template name="myOtherTemplate">
<h1> Lalalala </h1>
</template>
<template name="myTemplate">
{{> myOtherTemplate}} //injects the contents of myOtherTemplate
</template>
On another note, you also cannot nest Template instances within other Template instances.
Say that you want to register a helper function only after a certain template has been rendered.
Template.myTemplate.rendered = function({
Template.myTemplate.helpers({
key: "value",
anotherKey: "anotherValue"
});
});
^^ This also won't work.

Resources