I am quite new with Meteor but have really been enjoying it and this is my first reactive app that I am building.
I would like to know a way that I can remove the .main element when the user clicks or maybe a better way would be to remove the existing template (with main content) and then replace with another meteor template? Something like this would be simple and straightforward in html/js app (user clicks-> remove el from dom) but here it is not all that clear.
I am just looking to learn and for some insight on best practice.
//gallery.html
<template name="gallery">
<div class="main">First run info.... Only on first visit should user see this info.</div>
<div id="gallery">
<img src="{{selectedPhoto.url}}">
</div>
</template>
//gallery.js
firstRun = true;
Template.gallery.events({
'click .main' : function(){
$(".main").fadeOut();
firstRun = false;
}
})
if (Meteor.isClient) {
function showSelectedPhoto(photo){
var container = $('#gallery');
container.fadeOut(1000, function(){
Session.set('selectedPhoto', photo);
Template.gallery.rendered = function(){
var $gallery = $(this.lastNode);
if(!firstRun){
$(".main").css({display:"none"});
console.log("not");
}
setTimeout(function(){
$gallery.fadeIn(1000);
}, 1000)
}
});
}
Deps.autorun(function(){
selectedPhoto = Photos.findOne({active : true});
showSelectedPhoto(selectedPhoto);
});
Meteor.setInterval(function(){
selectedPhoto = Session.get('selectedPhoto');
//some selections happen here for getting photos.
Photos.update({_id: selectedPhoto._id}, { $set: { active: false } });
Photos.update({_id: newPhoto._id}, { $set: { active: true } });
}, 10000 );
}
If you want to hide or show an element conditionaly you should use the reactive behavior of Meteor: Add a condition to your template:
<template name="gallery">
{{#if isFirstRun}}
<div class="main">First run info.... Only on first visit should user see this info.</div>
{{/if}}
<div id="gallery">
<img src="{{selectedPhoto.url}}">
</div>
</template>
then add a helper to your template:
Template.gallery.isFirstRun = function(){
// because the Session variable will most probably be undefined the first time
return !Session.get("hasRun");
}
and change the action on click:
Template.gallery.events({
'click .main' : function(){
$(".main").fadeOut();
Session.set("hasRun", true);
}
})
you still get to fade out the element but then instead of hiding it or removing it and having it come back on the next render you ensure that it will never come back.
the render is triggered by changing the Sessionvariable, which is reactive.
I think using conditional templates is a better approach,
{{#if firstRun }}
<div class="main">First run info.... Only on first visit should user see this info.</div>
{{else}}
gallery ...
{{/if}}
You'll have to make firstRun a session variable, so that it'll trigger DOM updates.
Meteor is reactive. You don't need to write the logic for redrawing the DOM when the data changes. Just write the code that when X button is clicked, Y is removed from the database. That's it; you don't need to trouble yourself with any interface/DOM changes or template removal/redrawing or any of that. Whenever the data that underpins a template changes, Meteor automatically rerenders the template with the updated data. This is Meteor’s core feature.
Related
I have a use case (below) where I need to mount (if thats the correct term) a Vue.js component template that was inserted into the DOM via jQuery, I can setup a Mutation Observer or react to certain events that are triggered when the mutation happens.
I am using Vue.js v2
Here is a simple example I put together to illustrate the point:
live jsFiddle https://jsfiddle.net/w7q7b1bh/2/
The HTML below contains inlined-templates for two components
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<div id="app">
<!-- The use of inline-template is required for my solution to work -->
<simple-counter inline-template>
<button v-bind:style="style" v-on:click="add">clicks: {{ counter }}</button>
</simple-counter>
<simple-counter inline-template>
<button v-on:click="counter += 1">{{ counter }}</button>
</simple-counter>
</div>
<button id="mutate">Mutate</button>
The js:
// simple counter component
Vue.component('simple-counter', {
data: function() {
return {
counter: 0,
style: {
color: 'red',
width: '200px'
}
}
},
methods: {
add: function() {
this.counter = this.counter + 1;
this.style.color = this.style.color == 'red' ? 'green' : 'red';
}
}
})
// create the Vue instance
var initV = () => new Vue({
el: '#app'
});
// expose the instance for later use
window.v = initV();
// click handler that will add a new `simple-counter` template to the Vue.el scope
$('#mutate').click(function(){
$('#app').append(` <div is="simple-counter" inline-template>
<button v-bind:style="style" v-on:click="add">click to add: <span class="inactive" v-bind:class="{ active: true }">{{ counter }}</span></button></div>`)
// do something after the template is incerted
window.v.$destroy()
window.v = initV(); // does not work
})
As mentioned in the code, destroying the re-instantiating the Vue instance does not work, I understand why, the templates for the components are changed on first Vue instantiation to their final HTML, when you try and instantiate a second time, templates are not there, components are not mounted
I'd like to be able to find the newly added components after mutation and mount only those, is that possible? and how?
UPDATE:
I was able to find a way to do it via instantiating a new Vue instance with el set to the specific mutated part of the DOM as opposed to the whole #app tree:
$('#mutate').click(function(){
var appended =
$(`
<div is="simple-counter" inline-template>
<button v-bind:style="style" v-on:click="add">
click to add: {{ counter }}
</button>
</div>`
).appendTo($('#app'));
var newV = new Vue({el: appended[0]});
});
Seems to work, but also looks ugly and I am not sure what other implications this might have..
Use Case:
I am working on a way to write Vue.js components for a CMS called Adobe Experience Manager (AEM).
I write my components using inlined-template which gives me the advantage of SEO as well as server-side rendering using another templating language called HTL.
The way AEM authoring works is that, when a component is edited (via a dialog), that specific component is re-rendered on the server-side then injected back to the DOM to replace the old component, all done via Ajax and jQuery (no browser refresh).
Here is an example
AEM component template:
<button>${properties.buttonTitle}</button>
Here is what an author might do:
author visits the authoring page
opens the button component dialog to edit
changes the buttonTitle to "new button title"
Saves
upon saving, an ajax is sent, the component HTML is re-rendered on the server and returned is the new HTML. That HTML now replaces the old HTML via jQuery (mutates the DOM)
This is fine for static components, but if this was a Vue.js component, how do I dynamically mount it while keeping other components mounted.
An easy solution to this is to refresh the page... but that is just bad experience... There has to be a better way.
Thanks to #liam I was able to find an appropriate solution to my problem
After mutating the DOM with the HTML template, keep a reference to that template's parent element
for example:
var $template = $('<div is="simple-counter" inline-template> ..rest of template here.. <div>').appendTo('#app') // app is the Vue instance el or a child of it
Now you can create a new instance of your component and add $template to it as the el property
if my component was:
var simpleCounterComponent = Vue.component('simple-counter', {
data: function() {
return {
counter: 0,
style: {
color: 'red',
width: '200px'
}
}
},
methods: {
add: function() {
this.counter = this.counter + 1;
this.style.color = this.style.color == 'red' ? 'green' : 'red';
}
}
})
I can do:
var instance = new simpleCounterComponent({
el: $template.get(0) // getting an HTML element not a jQuery object
});
And this way, that newly added template has become a Vue component
Take a look at this fiddle for working example based on the question:
https://jsfiddle.net/947ojvnw/11/
One way to instantiate Vue components in runtime-generated HTML is:
var ComponentClass = Vue.extend({
template: '...',
});
var instance = new ComponentClass({
propsData: { name: value },
});
instance.$mount('#uid'); // HTML contains <... id="uid">
...
instance.$destroy(); // if HTML containing id="uid" is dropped
More here (I am not affiliated with this site)
https://css-tricks.com/creating-vue-js-component-instances-programmatically/
I am experiencing this weird scenario that I am unable to figure out what the problem is. There is a pagination for a collection which works fine when navigating. I have 5 documents in a collection with each to display per 2 on a page sing the pagination. Each document has a url link that when clicked it displays the full page for the document.
The challenge now is that if I click a document on the first page, it displays the full record, but if I navigate to the next page and click a document, it displays a blank page. I have tried all I could but haven't gotten what is to be made right.
These earlier posts are a build up to this present one: Publish and subscribe to a single object Meteor js, Meteor js custom pagination.
This is the helper
singleSchool: function () {
if (Meteor.userId()) {
let myslug = FlowRouter.getParam('myslug');
var subValues = Meteor.subscribe('SingleSchool', myslug );
if (myslug ) {
let Schools = SchoolDb.findOne({slug: myslug});
if (Schools && subValues.ready()) {
return Schools;
}
}
}
},
This is the blaze template
<template name="view">
{{#if currentUser}}
{{#if Template.subscriptionsReady }}
{{#with singleSchool}}
{{singleSchool._id}}
{{singleSchool.addschoolname}}
{{/with}}
{{/if}}
{{/if}}
</template>
try this;
onCreated function:
Template.view.onCreated(function(){
this.dynamicSlug = new ReactiveVar("");
this.autorun(()=>{
// When `myslug` changes, subscription will change dynamically.
this.dynamicSlug.set(FlowRouter.getParam('myslug'));
Meteor.subcribe('SingleSchool', this.dynamicSlug.get());
});
});
Helper
Template.view.helpers({
singleSchool(){
if (Meteor.userId()) {
let school = SchoolDb.findOne({slug: Template.instance().dynamicSlug.get()});
if (school) {
return school;
}
}
}
});
I have input which I use to filter my array of objects in Vue. I'm using Salvattore to build a grid of my filtered elements, but it doesn't work too well. I think I have to call rescanMediaQueries(); function after my v-model changes but can't figure how.
Here is my Vue instance:
var articlesVM = new Vue({
el: '#search',
data: {
articles: [],
searchInput: null
},
ready: function() {
this.$http.get('posts').then(function (response) {
this.articles = response.body;
});
}
});
And here is how I have built my search
<div class="container" id="search">
<div class="input-field col s6 m4">
<input v-model="searchInput" class="center-align" id="searchInput" type="text" >
<label class="center-align" for="searchInput"> search... </label>
</div>
<div id="search-grid" v-show="searchInput" data-columns>
<article v-for="article in articles | filterBy searchInput">
<div class="card">
<div class="card-image" v-if="article.media" v-html="article.media"></div>
<div class="card-content">
<h2 class="card-title center-align">
<a v-bind:href="article.link">{{ article.title }}</a>
</h2>
<div class="card-excerpt" v-html="article.excerpt"></div>
</div>
<div class="card-action">
<a v-bind:href="article.link"><?php _e('Read More', 'sage'); ?></a>
</div>
</div>
</article>
</div>
I did get the grid system working by adding watch option to my Vue, but every time I wrote something to my input and then erase it my filterBy method wouldn't work at all. It didn't populate any data even if I tried to retype the same keyword as earlier. Here is the watch option I used:
watch: {
searchInput: function (){
salvattore.rescanMediaQueries();
}
}
I think your problem is with the scoping of this in your success handler for http. Your articles object in Vue component is not getting any values from your http.get(..) success handler.
Inside your ready function, your http success handler should be as follows:
this.$http.get('posts').then(response => {
this.articles = response.body; // 'this' belongs to outside scope
});`
Alternatively you can also do:
var self = this; // self points to 'this' of Vue component
this.$http.get('posts').then(response => {
self.articles = response.body; // 'self' points to 'this' of outside scope
});`
Another similar issue: https://stackoverflow.com/a/40090728/654825
One more thing - it is preferable to define data as a function, as follows:
var articlesVM = new Vue({
el: '#search',
data: function() {
return {
articles: [],
searchInput: null
}
},
...
}
This ensures that your articles object is unique to this instance of the component (when you use the same component at multiple places within your app).
Edited after comment #1
The following code seems to work alright, the watch function works flawlessly:
var vm = new Vue({
el: '#search',
template: `<input v-model="searchInput" class="center-align" id="searchInput" type="text" >`,
data: {
searchInput: ""
},
watch: {
searchInput: function() {
console.log("searchInput changed to " + this.searchInput);
}
}
})
The input in template is an exact copy of your version - I have even set the id along with v-model, though I do not see the reason to set an id
Vue.js version: 2.0.3
I am unable to see any further, based on details in the question. Can you check if your code matches with the one above and see if you can get the console debugging messages?
Edited after comment #4, #5
Here is another thought which you need to verify:
Role of vue.js: Render the DOM
Role of salvattore plugin: Make the DOM layouts using CSS only
Assuming the above is true for salvattore plugin, and hopefully it does not mess with vue.js observers / getters / setters, then you can do the following: provide a time delay of about 50 ms so that vue.js completes the rendering, and then call the salvattore plugin to perform the layouts.
So your watch function needs to be as follows:
watch: {
searchInput: function (){
setTimeout(function(){
salvattore.rescanMediaQueries();
}, 50);
}
}
Alternatively you may also use Vue.nexttick() as follows:
Vue.nextTick(function () {
// DOM updated
})
The nextTick is documented here: https://vuejs.org/api/#Vue-nextTick
I do not know if you may need to provide a little bit of extra time for salvattore plugin to start the layouts, but one of the above should work out.
Let me know if it works!
My intention is to retrieve one random entry from a collection and display it on the website - if all sentences are through (read: the user has "seen" them), display something else (therefore a dummy sentence gets returned). But, on server start and on button-click events, this helper gets fired at least twice. Here is some code:
In client.js:
Template.registerHelper('random_sentence', function() {
fetched = _.shuffle(Sentences.find({
users: {
$nin: [this.userId]
}
}).fetch())[0];
if (fetched === undefined) {
return {
sentence: "done",
_id: 0,
done: true
};
}
Session.set('question', fetched._id);
console.log(fetched);
return fetched;
});
The helper function for the template:
sent: function(){
sent = Session.get('question');
return Sentences.findOne(sent);
}
in main template:
{{#with random_sentence}}
{{#if done}}
<!-- Display something else -->
{{else}}
<div class="container">
{{> question}}
</div>
{{/if}}
{{/with}}
the "question" template:
<div class="well">
<div class="panel-body text-center">
<h3>{{sent.sentence}}</h3>
</div>
</div>
If I don't return anything in the "random_sentences"-function,nothing get's displayed.
I don't know where my "logic failure" is situated? I'm new to meteor - so I might overlook something obvious.
Thanks in advance :-)
UPDATE: This is how I intended to get the new sentence and display it:
Template.answer.events({
'click': function(event) {
var text = event.target.getAttribute('id');
if (text !== null) {
var question = Session.get('question');
var setModifier = {
$inc: {}
};
setModifier.$inc[text] = 1;
Sentences.update(question, setModifier);
Meteor.call('update_user', question);
Notifications.success('Danke!', 'Deine Beurteilung wurde gespeichert.');
Blaze.render(Template.question, document.head);
}
}
});
In server.js (updating the question and a counter on the user):
Meteor.methods({
update_user: function(question) {
Sentences.update(question, {
$push: {
"users": this.userId
}
});
Meteor.users.update({
_id: this.userId
}, {
$inc: {
"profile.counter": 1
}
});
},
});
I found the Blaze.render function somewhere on the web. the "document.head" part is simply because this function needs a DOM Element to render to, and since document.body just "multiplies" the body, I ust moved it to the head. (DOM logic isn't my strong part).
An Idea I had: would it make the whole idea simpler to implement with iron-router? atm. I wanted to create a "one-page app" - I therefore thought that I don't need a router there.
Another problem: Getting this logic to work (User gets one random sentence, which he has not seen) and publishing small sets of the collection (so the Client don't have to download 5 MB of data before using).
Template helpers can be called multiple times so it's good to avoid making them stateful. You're better off selecting the random entry in an onCreated or onRendered template handler. There you can do your random select, update the state, and put your choice in a Session variable to be retrieved by the helper.
I have an input that actively edits the name of a model.
The problem is that the input accepts the changes if I begin to type into the input.
So writing a categoryName (an attribute of recordCategory) with a value of "Something Else" would be a giant chore because I would need to refocus on the edit-recordCategory input after every letter I type. So if i would be focused on the input and I would quickly type "Some", it would accept the 'S' before unfocusing me out of the input and resorting the recordCategory in the list based on it's current value, which would only be "S".
Here's a more detailed example of my code.
{{#each searchResults itemController="recordCategory"}}
<div id="hoveredRow" {{bind-attr class="isEditing:editing"}}>
{{#if isEditing}}
<div class="input-standard">
{{edit-recordCategory value=categoryName focus-out="acceptChanges"
insert-newline="acceptChanges"}}
</div>
{{else}}
{{categoryName}}
{{/if}}
</div>
{{/each}}
This is my controller
isEditing: false,
actions: {
editrecordCategory: function(recordCategory){
this.set('isEditing', true);
console.log(this.get('isEditing is toggling'))
},
acceptChanges: function() {
this.set('isEditing', false);
if (Ember.isEmpty(this.get('model.categoryName'))) {
this.send('removerecordCategory');
} else {
this.get('model').save();
}
console.log(this.get('isEditing'))
},
}
and then the view that defines edit-recordCategory
VpcYeoman.EditRecordCategoryView = Ember.TextField.extend({
didInsertElement: function() {
this.$().focus();
}
});
Ember.Handlebars.helper('edit-recordCategory', VpcYeoman.EditRecordCategoryView);
EDIT:
After implementing GJK's version of the 'acceptChanges' action. I was receiving the same problem.
TEST 1
I commented out the acceptChanges action and both of it's references in {{edit-recordCategory value=categoryName focus-out="acceptChanges" insert-newline="acceptChanges"}} making it just {{edit-recordCategory value=categoryName}}. The same problem is still happening. This leads me to believe that the problem is not in the way acceptChanges was written.
There was a point where my original 'acceptChanges' action and its use in
{{edit-recordCategory value=categoryName focus-out="acceptChanges"
insert-newline="acceptChanges"}}
worked perfectly.
TEST 2
On top of taking out any reference of 'acceptChanges', i removed the {{#if Editing}} conditional. The
{{edit-recordCategory value=categoryName focus-out="acceptChanges"
insert-newline="acceptChanges"}}
did not disappear upon typing (as expected with there being no ember conditional, but the {{edit-recordCategory}} still auto submits when I type. It should also be noted that this list of recordCategories sorts itself, so upon accepting the edit, i'm focused out of {{edit-recordCategory}} and the object resorts itself based on it's new categoryName value
Problem Found! But it breaks my filter bar.
Once i commented out this function
searchResults: function() {
var searchTerm = this.get('searchTerm');
var regExp = new RegExp(searchTerm,'i');
// We use `this.filter` because the contents of `this` is an array of objects
var filteredResults = this.filter(function(category) {
return regExp.test(category.get('categoryName'));
});
return filteredResults;
}.property('#each.categoryName', 'searchTerm'),
and took 'searchResults' out of {{#each searchResults itemController="recordCategory"}} to editing worked smoothly, but now my search bar filter is not working.
Your categoryName property is on your model, which means you can override it in your controller. You'll want to use a temporary property on your controller to solve your issue.
recordCategory: '',
actions: {
acceptChanges: function() {
var recordCategory = this.get('recordCategory');
this.set('model.recordCategory', recordCategory);
}
}