VueJs - How to access DOM property of an element from $refs - dom

I have an element
<tbody ref="tbody">
<tr class="row" :ref="userIndex" v-for="(userData, uid, userIndex) in users" :key="uid">
in my template. I need to access/edit the DOM property like scrollTop, verticalOffset of <tr> element. How can I achieve this?
I have tried to access using this.$refs[userIndex][0].$el but its not working. I can see all the properties in the console but I am unable to access them. However this.$refs.tbody.scrollTop works.
Below is the snap showing console.log(this.$refs)
console.log(this.$refs[userIndex])
console.log(this.$refs[userIndex][0])
As you can see when I use this.$refs[userIndex][0] I don't see the DOM properties

A $ref object will only have a $el property if it is a Vue component. If you add a ref attribute to a regular element, the $ref will a reference to that DOM Element.
Simply reference this.$refs[userIndex][0] instead of this.$refs[userIndex][0].$el.
To see the properties of that element in the console, you'll need to use console.dir instead of console.log. See this post.
But, you can access properties of the element like you would any other object. So, you could log the scrollTop, for instance, via console.log(this.$refs[userIndex][0].scrollTop).

I don't think verticalOffset exists. offsetTop does. To console log an Dom element and its property, use console.dir
Open the browser console and run this working snippet:
var app = new Vue({
el: '#app',
data: {
users: {
first: {
name: "Louise"
},
second: {
name: "Michelle"
}
}
},
mounted() {
console.dir(this.$refs[1][0])
console.log('property: ', this.$refs[1][0].offsetTop)
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<table><tbody ref="tbody">
<tr :ref="userIndex" v-for="(userData, uid, userIndex) in users" :key="uid">
<td>{{userData}}: {{userIndex}}</td>
</tr>
</tbody>
</table>
</div>

Related

How to select an element inside a dom-module in polymer 1.0?

I have the following dom-module that I am trying to create interactions for.
<dom-module is="bw-image-upload">
<template>
<vaadin-upload id="uploader"
target="{{ API_URL}}/images/upload"
method="POST"
max-files="1"
max-file-size="200000"
accept="image/*"
upload-success="uploadResponseHandler"
file-reject="errorHandler"
>
</vaadin-upload>
</template>
<script>
Polymer({
is: 'bw-image-upload',
properties: {
image: String,
notify: true
}
});
var uploader = document.querySelector('#uploader');
uploader.addEventListener('upload-before', function(event) {
console.log(event);
});
</script>
</dom-module>
I want to select the vaadin-upload element by it's ID but it returns a null and I am confused on why it is returning null.
How do I select an element like this in Polymer?
If the element has an id and is statically added to the template, you can use
var uploader = this.$.uploader;
to get a reference to an element with the id uploader.
If the element is inside <template is="dom-if">, <template is="dom-repeate"> or otherwise dynamically created this is not supported.
In such cases you can use
var uploader = this.$$('#uploader');
this.$$(...) provides full CSS selector support and returns the first matching element, while this.$... only supports IDs.

Datatables with Meteor using Collections Join

I want to display the data in a tabular fashion, Data will be fetched using the joins of collection from Mongo DB , I have some experience in Datatables that I have used in my previous projects
I have been trying with lots of Meteor stuff to accomplish this.
What I tried and What is the result:
I am using loftsteinn:datatables-bootstrap3 (https://github.com/oskarszoon/meteor-datatables-bootstrap3/) I am trying to display the data using joining of two collections, for Joining of collections I am using : https://atmospherejs.com/reywood/publish-composite.
The Issue : as the data gets fetched and the page gets rendered with the table it shows 0 records, but after a few seconds rows get populated and datatable gets filled but still shows 0 records.
To Counter this issue I have to set timeout for few seconds and then it shows correctly.
Is there any better way, as I feel that in case the data gets increased, I may face issues again.
Possible Solutions with Other Packages?
Is anybody has expirience in Joining of Collections and displaying correctly in the tabular format with Pagination, Sorting and Search?
I would Appriciate any help in this.
CODE:
TEMPLATE
<template name="testdatatable">
{{#if Template.subscriptionsReady}}
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="myTable">
<thead>
<tr>
<th>Todos Name</th>
<th>List Name</th>
</tr>
</thead>
<tbody>
{{#each todos}}
<tr>
<td>{{name}}</td>
<td>{{lists.name}}</td>
</tr>
{{/each}}
</tbody>
</table>
{{else}}
<div class="loading">{{>spinner}}</div>
{{/if}}
</template>
TEMPLATE HELPER
Template.testdatatable.helpers({
todos: function() {
console.log(Todos.find());
return Todos.find();
},
lists: function() {
return Lists.findOne(this.listId);
}
});
PUBLISH COMPOSITE using ( reywood:publish-composite )
Meteor.publishComposite('tabular_Todos', {
find: function () {
return Todos.find();
},
children: [
{
find: function(todos) {
return Lists.find({_id: todos.listId });
}
}
]
});
ROUTING USING (iron Router)
Router.route('/testdatatable', {
name: 'testdatatable',
template: 'testdatatable',
onAfterAction: function(){
calltestdatatable();
},
subscriptions: function(){
return Meteor.subscribe('tabular_Todos');
}
});
OTHER FUNCTIONS
ON RENDERED
Template.testdatatable.onRendered(function(){
setTimeout(calldatatable, 2000);
});
SETTING A TIMEOUT TO DELAY THE DATATABLE
function calltestdatatable(){
setTimeout(calldatatable, 2000);
}
DATATABLE INITIALISATION
function calldatatable(){
$('#myTable').DataTable();
}
DATABASE
todos Collection
lists Collection
Thanks and Best Regards,
Manu
here is my route that fixes the problem :
Router.route('testdatatable', {
path: '/testdatatable',
name: 'testdatatable',
template: 'testdatatable',
waitOn: function() {
return [
Meteor.subscribe('tabular_Todos')
];
},
subscriptions: function(){
return Meteor.subscribe('tabular_Todos');
}
});
and template
Template.testdatatable.onRendered(function(){
$('#myTable').dataTable();
});
(as I used the --example todos, I had to change {{name}} as {{text}} to display the todo text)
Search, pagination, sorting works fine with meteor add lc3t35:datatables-bootstrap3 !
Answer to your first question.
your data needs to come into minimongo first, then client side will be able to render those data. As a workaround you can use loading animation. a quick solution would be using sacha:spin package. and your Blaze code will be something similar to this.
{{#if Template.subscriptionsReady}}
// load your view
{{else}}
<div class="loading">{{>spinner}}</div>
{{/if}}
your second problem is that ,db gets filled but table shows nothing except row skeleton. It's most probably because you have either problems with helper function or in the Blaze view. As you've not posted any code, it's hard to identify problem.
And to other questions: there are quite good numbers of packages for pagination and search. checkout atmosphere. you'll find some popular packages like pages and easy-search. you need to decide which suits for your project.

How to reach _id of document when it's in the parent data context?

This seems like an open-and-shut case for Template.parentData(), but to this day I've never once managed to get that bad boy working properly.
What I want is an event that updates a document depending on which button was clicked, but the buttons are themselves dependent on an array buried deeper in the document, where the _id doesn't exist.
Here's what I have:
First, a helper that sets the context peopleList:
Template.people.helpers({
peopleList: function() {
return People.find()
}
Which I use to iterate through in the HTML, printing out the first and last name of each person stored in the database, as well as their favorite colors (extraneous markup removed):
{{#each peopleList}}
<li>
{{firstName}} {{lastName}}
{{#each favoriteColors}} <button>{{this}}</button> {{/each}}
</li>
{{/each}}
It should be noted at this point that favoriteColors is a key inside the document which holds an array. So the whole thing looks something like this:
{
firstName: "Johnny",
lastName: "Boy",
favoriteColors: ["red", "blue", "blanchedAlmond"]
}
Imagine now that I want to be able to press any of these buttons, which hold the favorite colors, to set the, uh, super-duper favorite color or something. So a button click on blanchedAlmond should update the document, adding the key masterColor with the value blanchedAlmond.
The event:
'click button': function() {
var masterColor = ????
var docId = ????
Meteor.call('setMasterColor', masterColor, docId)
}
I could provide HTML data-tags that hold the color value (because this inside the event spits out some weird array with each letter separated for some reason) and even the _id with {{../_id}}, but that feels like cheating, and I really want to learn how to do the same thing inside a helper or an event.
I strongly feel like this would be a case for Template.parentData() but it returns nothing at all when I console.dir it. What should I do?
The confusion around parentData has to do with the event context. The event is attached to the template whose context is something that isn't a person or a color. Whenever you get the feeling that you need to start littering your code with data- attributes, the answer is nearly always to add more templates. For example:
html
<template name="myTemplate">
<ul>
{{#each peopleList}}
{{> person}}
{{/each}}
</ul>
</template>
<template name="person">
<li>
{{firstName}} {{lastName}}
{{#each favoriteColors}}
{{> color}}
{{/each}}
</li>
</template>
<template name="color">
<button>{{this}}</button>
</template>
js
Template.color.events({
'click button': function() {
// this context is a color - remember to convert it to a string
var masterColor = String(this);
// the parent context is a person
var docId = Template.parentData(1)._id;
return Meteor.call('setMasterColor', masterColor, docId);
}
});

Couldn't manipulate Images.find() in CollectionFS for MeteorJS app

My app is sort of like TelescopeJS, but a lot simpler. I'm trying to echo the particular image that has been added in the post-adding form which takes an input of the name of the post, picture, categories and description. It has 2 collections, one for Articles and the other for Images (NOT a mongo collection, it's an FS collection.) The articles collection stores the name,description and category name and the other one stores image. **My Problem is: ** in the FS collection doc, the loop
{{#each images}}
<img src="{{this.url}}" alt="" class="thumbnail" />
{{/each}}
Where images: returns Images.find({}) and my articles code is :
{{#each articles}}
<li style="margin-right: 1%;">{{>article}}</li>
{{/each}}
Where articles: returns Articles.find({})
MY articles template HAS the images loop and this causes ALL THE IMAGES in the collection to be shown in one post. I just want specific images to be shown for the specific post.
These are the events:
'change .img': function(event, template) {
FS.Utility.eachFile(event, function(file) {
Images.insert(file, function (err, fileObj) {
//Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
});
});
},
'click .save':function(evt,tmpl){
var description = tmpl.find('.description').value;
var name = tmpl.find('.name').value;
var date=new Date();
var cat = tmpl.find('.selectCat').value;
Articles.insert({
description:description,
name:name,
time:date.toLocaleDateString()+' at '+date.toLocaleTimeString(),
author:Meteor.userId(),
userEmail:Meteor.user().username,
category:cat,
});
}
<template name="article">
{{#each images}}
<img src="{{this.url}}" alt="" class="thumbnail" />
{{/each}}
Here goes the {{name_of_post}}
Here {{the_category}}
Here {{the_description}}
</template>
So what happens is, all the images that I've uploaded so far shows in one post and all the posts' picture looks the same. Help please!
You should know that fsFile support Metadata so maybe you don't need the Articles Collection
So we can make a new eventHandler.
'click .save':function(evt,tmpl){
var description = tmpl.find('.description').value,
file = $('#uploadImagePost').get(0).files[0], //here we store the current file on the <input type="file">
name = tmpl.find('.name').value,
date=new Date(),
cat = tmpl.find('.selectCat').value,
fsFile = new FS.File(file); // we create an FS.File instance based on our file
fsFile.metadata = { //this is how we add Metadata aka Text to our files
description:description,
name:name,
time:date.toLocaleDateString()+' at '+date.toLocaleTimeString(),
author:Meteor.userId(),
userEmail:Meteor.user().username,
category:cat,
}
Images.insert(fsFile,function(err,result){
if(!err){
console.log(result) // here you should see the new fsFile instance
}
});
}
This is how our new event will look, now our .save button insert everything on the same collection.
This is how we can access to the FS.File instances fields using the keyword 'metadata.fieldName'.
For example.
Teamplate.name.helpers({
showCategory:function(){
// var category = Session.get('currentCategory') you can pass whatever data
// you want here from a select on the html or whatever.
//lets say our var its equal to 'Music'
return Images.find({'metadata.category':category});
}
})
Now we use that helper on the html like any normal collection
<template name="example">
{{#each showCategory}}
Hi my category is {{metadata.category}} <!-- we access the metadata fields like any normal field on other collection just remember to use the 'metadata'keyword -->
This is my image <img src="{{this.url}}" >
{{/each}}
</template>

Backbone.js & Handlebars.js with RESTful API

I am trying to use Backbone.js with Handlebars.js to consume and display a custome JSON API.
Data is definitely being consumed and and added into the Collection.
The template renders but the table has no data in it (one completely empty row).
How would I go about debugging this?
Router
'showStatement': function() {
new app.StatementView({collection: new app.StatementCollection()});
}
Collection
app.StatementCollection = Backbone.Collection.extend({
model: app.Transaction,
url: 'http://localhost/api/public/out/123456/statement',
initialize: function() {
console.log('Init app.StatementCollection');
}
});
Model
app.Transaction = Backbone.Model.extend({
/*
defaults: {
vendor: 'Unknown',
amount: 'Unknown',
currency: 'Unknown',
date: 'Unknown'
}
*/
});
View
app.StatementView = Backbone.View.extend({
el: '#page',
template: Handlebars.getTemplate( 'account_statement' ),
initialize: function() {
console.info(this.collection);
this.render();
this.listenTo(this.collection, 'add', this.render);
this.listenTo(this.collection, 'reset', this.render);
this.collection.fetch();
},
// render library by rendering each book in its collection
render: function() {
this.$el.html( this.template( JSON.stringify(this.collection.toJSON())) ); // <------ pretty sure the problem lies here?!?
console.log('col', JSON.stringify(this.collection.toJSON()) ); // <------ the output from this is shown at the bottom
return this;
}
});
Handlebars Template
{{#if statement}}
<h1>Your Statement</h1>
<table border="1">
<thead>
<th>Date</th>
<th>Name</th>
<th>Amount</th>
</thead>
<tbody>
{{#each statement}}
{{debug}}
<tr>
<td>{{this.vendor}}</td>
<td>{{currency this.currency}}{{this.amount}}</td>
<td><time class="format-date" datetime="{{this.date}}">{{this.date}}<time></td>
</tr>
{{/each}}
</tbody>
</table>
{{else}}
<p class="warning">Sorry, nothing to show.</p>
{{/if}}
This is what my API's JSON looks like:
{"status":true,"result":[{"id":1,"vendor":"Jessops","amount":595.99,"currency":"GBP","date":"2012-11-01 04:57:04"},{"id":2,"vendor":"Starbucks","amount":6.99,"currency":"GBP","date":"2012-11-02 04:57:04"},{"id":3,"vendor":"Superdry","amount":155.99,"currency":"GBP","date":"2012-11-03 04:57:04"},{"id":6,"vendor":"Reebok Outlet","amount":205.99,"currency":"USD","date":"2012-11-05 04:57:04"}]}
Output from console.log('col', JSON.stringify(this.collection.toJSON()) );
col [{"status":true,"result":[{"id":1,"vendor":"Jessops","amount":595.99,"currency":"GBP","date":"2012-11-01 04:57:04"},{"id":2,"vendor":"Starbucks","amount":6.99,"currency":"GBP","date":"2012-11-02 04:57:04"},{"id":3,"vendor":"Superdry","amount":155.99,"currency":"GBP","date":"2012-11-03 04:57:04"},{"id":6,"vendor":"Reebok Outlet","amount":205.99,"currency":"USD","date":"2012-11-05 04:57:04"}]}]
EDIT:
I have now found that changing my render function to the following works:
render: function() {
data = this.collection.toJSON();
this.$el.html(this.template( {statement: data[0]} ));
return this;
}
This suggests that my JSON output is wrong. How can I improve my JSON to reduce the need for the [0]?
It looks like your API returns some 'meta' information (the status : true part) along with the data about the collection, and that your real data lives in the result array. I think Backbone is assuming that your data is just a single item, and it putting it into an array since it is being fed into a collection object. That's why you're needing to use data[0] to pull the first item out of that array.
I think you'd either want o modify your json so that the array currently returned in result is the top level element. Of you'd need to find a way to tell Backbone that your data lives in the result element, not at the top level.