Change value of reactive variable in hook in Meteor - javascript

I have
Template.templateName.onCreated(function() {
this.variableName = new ReactiveVar;
this.variableName.set(true);
});
and in templateName I have an autoform. I need to set the reactive variable variableName to false when the autoform is submitted.
I have tried
AutoForm.hooks({
myForm: {
onSuccess: function(operation, result) {
this.variableName.set(false);
},
}
});
but it doesn't work since this. does not refer to the template templateName as it does in helpers and events. It would have worked if I used sessions instead since these are not limited/scoped to specific templates.
What can I do to change the reactive variable in an autoform hook?
I have also tried
AutoForm.hooks({
myForm: {
onSuccess: function(operation, result) {
this.template.variableName.set(false);
this.template.parent.variableName.set(false);
this.template.parent().variableName.set(false);
this.template.parentData.variableName.set(false);
this.template.parentData().variableName.set(false);
this.template.parentView.variableName.set(false);
this.template.parentView().variableName.set(false);
},
}
});
When using console.log(this.template) it does print an object. If I use console.log(this.template.data) I get
Object {id: "myForm", collection: "Meteor.users", type: "update", doc: Object, validation: "submitThenKeyup"…}
I use the reactive variable variableName to determine whether to either show the editable form or the nice presentation of data for the user. Maybe there is another better way to do this.

Edit of onCreated:
Template.templateName.onCreated(function() {
this.variableName = new ReactiveVar(false);
});
You may want to add a helper function to grab the Template instance:
Template.templateName.helpers({
getVariableName: function() {
return Template.instance().variableName.get();
}
});
and then you could potentially call within your form logic
AutoForm.hooks({
myForm: {
onSuccess: function(operation, result) {
Template.getVariableName.set(false);
},
}
});
The MeteorChef has a great article about reactive variables/dictionaries Reactive Variables.

If people stumble upon this for a solution, based this thread I as able to access the parents Reactive Dict/Reactive Variable after installing aldeed:template-extension like so
AutoForm.hooks({
postFormId: {
//onSuccess hook of my post form
onSuccess: function(formType, result) {
this.template.parent().reactiveDictVariable.set('imgId', 'newValueSetOnSuccess');
//Or reactive var, and depending on your hierarchy
//this.template.parent().parent().yourReactiveVar.set(undefined);
}
}
});
Here is Html and JS for reference.
<template name="postsTemplate">
{{#autoForm schema=postFormSchema id="postFormId" type="method" meteormethod="addPost"}}
<!-- other autoform stuff -->
This is reactive variable used in template -- {{imgId}}
{{/autoForm}}
</template>
Template.postsTemplate.created = function() {
//Using reactive-dict package here
this.reactiveDictVariable = new ReactiveDict();
this.reactiveDictVariable.set('imgId', undefined);
};
Template.posts.events(
"change .some-class": function(event, template) {
//other stuff
template.postImgState.set('imgId', 'something');
}

Related

How to update Vue component when promise resolve AND passing props to nested children

I have parent and child components. Parent's data is populated after an ajax call, that I want to pass to child as a props.
I tried different solutions, I will post two, but not yet working : could you please pin-point the error?
The component does react to changes. I also need to ensure that props are correctly passed to child and its nested children.
Attempts:
If I don't use 'v-if' directive, I will get an error for :query is
passed through as null.
So I use v-if (see version below)
and update the rendering, but it does not react and stay empty (even
though data is properly updated).
I also tried to initialize the query data as computed without using
the v-if directive, because after all I just need to cache the result
of the premise.
I also tried to emit an event on a bus, but the component does not
react.
Finally I tried to make the component reactive by making use of a
:key (e.g. :key="ready") that should make the component reactive when
the :key changes. But still no effect.
Template:
<template>
<div v-if="isLoaded()">
<input>
<metroline></metroline>
<grid :query="query"></grid>
</div>
</template>
script:
export default {
data() {
return {
ready : false,
query : null
}
},
components : {
metroline : Metroline,
grid : Grid
},
methods: {
isLoaded() {
return this.ready
},
firstQuery( uid, limit, offset) {
var url = // my url
// using Jquery to handle cross origin issues, solving with jsonp callback...
return $.ajax({
url : url,
dataType: 'jsonp',
jsonpCallback: 'callback',
crossDomain: true
})
}
},
created() {
var vm = self;
this.firstQuery(...)
.then(function(data){
this.query = data;
console.log('firstQuery', this.query);
// attempts to pass through the query
// bus.$emit('add-query', this.query);
this.ready = true;
self.isLoaded(); // using a self variable, temporarily, jquery deferred messed up with this; however the this.query of vue instance is properly updated
})
}
}
In created hook assign the component instance this to a a variable called that and access it inside the callback because in the callback you're outside the vue component context (this):
created() {
var vm = self;
var that=this;
this.firstQuery(...)
.then(function(data){
that.query = data;
console.log('firstQuery', this.query);
that.ready = true;
self.isLoaded();
})
}
}

How to fix FlowRouter.getParam from being 'undefined'

I am adding a new page to a website, and I am copying the code that already exists and is currently working in the website. Why is the FlowRouter.getParam coming up undefined when it works everywhere else?
client/JobInvoice.js
import { Invoices } from '../../../imports/api/Invoice/Invoice';
Template.InvoicePage.onCreated(function(){
const user = FlowRouter.getParam('_id');
console.log(user);
this.subscribe('invoices', user);
});
lib/router.js
Accounts.onLogout(function(){
FlowRouter.go('home');
});
FlowRouter.notFound = {
action: function() {
FlowRouter.go('/404');
}
};
const loggedIn = FlowRouter.group({
prefix: '/secure'
});
loggedIn.route( '/invoice', {
name: 'invoice',
action() {
BlazeLayout.render('FullWithHeader', {main:
'InvoicePage'});
}
});
What am I missing?
FlowRouter allows you to define routes with dynamic attributes (path-to-regexp), which are often representing document ids or other dynamic attributes.
For example
FlowRouter.route('/invoice/:docId', { ... })
would define a route that matches a pattern like /invoice/9a23bf3uiui3big and you usually use it to render templates for single documents.
Now if you want to access the document id as param docId inside the corresponding Template you would use FlowRouter.getParam('docId') and it would return for the above route 9a23bf3uiui3big.
Since your route definitions lacks a dynamic property, there is no param to be received by FlowRouter.getParam.
A possible fix would be
loggedIn.route( '/invoice/:_id', {
name: 'invoice',
action() {
BlazeLayout.render('FullWithHeader', {main:
'InvoicePage'});
}
});
to access it the same way you do for the other templates.
Readings
https://github.com/kadirahq/flow-router#flowroutergetparamparamname
Here is what I ended up doing and it works.
loggedIn.route( '/invoice/:id', {
name: 'invoice',
action() {
BlazeLayout.render('FullWithHeader', {main: 'InvoicePage'});
}
});

Polymer dom-repeat issue

While rendering with Polymer an array of objects, it keeps launching me an exception.
Here's the data model retrieved from server:
{
"lastUpdate":"yyyy-MM-ddTHH:mm:ss.mmm",
"info": [
{
"title": "Some nice title"
},
...
]
}
Here's my Polymer component template:
<dom-module is="items-list">
<template>
<dl>
<dt>last update:</dt>
<dd>[[$response.lastUpdate]]</dd>
<dt>total items:</dt>
<dd>[[$response.info.length]]</dd>
</dl>
<template is="dom-repeat" items="{{$response.info}}">
{{index}}: {{item.title}}
</template>
</template>
<script src="controller.js"></script>
</dom-module>
And here's the controller:
'use strict';
Polymer(
{
properties: {
info: {
type: Array
},
$response: {
type: Object,
observer: '_gotResponse'
}
},
_gotResponse: function(response)
{
console.log(response);
if (response.info.length)
{
try
{
//here I try to set info value
}
catch(e)
{
console.error(e);
}
}
},
ready: function()
{
//set some default value for info
},
attached: function()
{
//here I request the service for the info
}
}
);
If tried to set info value as:
this.info = response.info;
this.set('info', response.info);
this.push('info', response.info[i]); //inside a loop
But the result breaks after rendering the first item, the exception launched is:
"Uncaught TypeError: Cannot read property 'value' of null"
If info === $response.info then why not just use items={{info}} in the repeat?
edit:
Try to modify your code in the following way.
'use strict';
Polymer({
properties: {
$response: {
type: Object
}
},
_gotResponse: function(response)
{
console.log(response);
...
this.$response = response
...
},
attached: function()
{
//here I request the service for the info
someAjaxFn(someParam, res => this._gotResponse(res));
}
});
You don't need an observer in this case. You only use an explicit observer when the implicit ones don't/won't work. I.e. fullName:{type:String, observer:_getFirstLastName}
or
value:{type:String, observer:_storeOldVar}
...
_storeOldVar(newValue, oldValue) {
this.oldValue = oldValue;
}
if you are updating the entire array, ie this.info, then you simple use this.info = whatever once within your function. If you don't want to update the entire array, just some element within it, then you will want to use polymer's native array mutation methods as JS array method doesn't trigger the observer.
Again, since your template doesn't use info, then you don't need the property info. If you want to keep info, then don't store info within $response. In fact, $ has special meaning in polymer so try not to name properties with it. you can simply use the property info and lastUpdate for your polymer.
Last note, beware of variable scoping when you invoke functions from polymer. Since functions within polymer instances often use this to refer to itself, it may cause
Uncaught TypeError: Cannot read property 'value' ..."
as this no longer refers to the polymer instance at the time of resolve.
For example, suppose your host html is
...
<items-list id='iList'></items-list>
<script>
iList._gotResponse(json); // this will work.
setTimeout(() => iList.gotResponse(json),0); //this will also work.
function wrap (fn) {fn(json)}
wrap (iList._gotResponse); //TypeError: Cannot read property '$response' of undefined.
function wrap2(that, fn) {fn.bind(that)(json)}
wrap2 (iList,iList._gotResponse); // OK!
wrap (p=>iList._gotResponse(p)) //OK too!!
wrap (function (p) {iList._gotResponse(p)}) //OK, I think you got the idea.
</script>

Ember-data: model refresh on DS.Store.createRecord

Embsters!
I am trying to figure out why my model isn't refreshed after I create a new record and save it to the store.
My route computes the model as follows:
model: function (params) {
var postID = params.post_id,
userID = this.get('session.currentUser.id');
var post = this.store.findRecord('post', postID) ;
var followings = this.store.query('post-following', {
filter: { post: postID }
}) ;
var userFollowing = this.store.queryRecord('post-following', {
filter: { post: postID, user: userID }
}) ;
return new Ember.RSVP.hash({
post: post,
followings: followings,
userFollowing: userFollowing
});
}
My template then renders a list and a button:
{{#each model.followings as |following|}}
...
{{/each}}
{{#if model.userFollowing}}
<button {{action 'follow'}}>Follow</button>
{{else}}
<button {{action 'unFollow'}}>Unfollow</button>
{{/if}}
And my controller creates/deletes the relevant post-following record:
actions: {
follow: function () {
var user = this.get('session.currentUser'),
post = this.get('model.post') ;
this.store.createRecord('post-following', {
user: user,
post: post
}).save();
},
unFollow: function () {
this.get('model.userFollowing').destroyRecord() ;
}
}
When I click the [Follow] button:
a successful POST request is sent
the button is not updated
the list is not updated
When I (refresh the page then) click the [Unfollow] button:
a successful DELETE request is sent
the button is not updated
the list is updated
Do you have any idea of what I'm doing wrong?
Could it be a problem with my payload?
EDIT: Solved!
Well, it sounds like I was expecting too much from ember.
The framework won't automatically update my post-followings array on store.createRecord('post-following', {...}) call.
I then adjusted my controller logic to "manually" update my model:
// in follow action…
userFollowing.save().then( function(){
var followings = store.query('post-following', {
filter: { post: postID }
}).then( function (followings) {
_this.set('model.userFollowing', userFollowing);
_this.set('model.followings', followings);
}) ;
});
// in unFollow action…
userFollowing.destroyRecord().then( function () {
_this.set('model.userFollowing', null);
_this.notifyPropertyChange('model.followings') ;
});
Please note that my backend API design has been criticized by #duizendnegen (see comments). More best practices in this article.
Thanks you for all your help !!!
Brou
For these kind of questions, it really helps to have a smaller, replicated problem (e.g. through Ember Twiddle)
Fundamentally, the new post-following record doesn't match the filter: it is filtered for an attribute { post: 123 } and your post-following object contains something in the lines of { post: { id: 123, name: "" } }. Moreover, your post-following object doesn't contain a property called filter or what it could be - i.e. the query it executes to the server are different than those you want to filter by on the client.
My approach here would be to, as a response to the follow and unfollow actions, update the model, both the userFollowing and followings.
Your issue is that you aren't re-setting the property model to point to the newly created object. You are always accessing the same model property, even after creating a new one.
First thing to be aware of is that, after the model hook in your route, the setupController hook is called that executes:
controller.set('model', resolvedModel)
meaning that the model property on your controller is, by default, set every time the route loads (the model hook resolves). However, this doesn't happen after you create a new record so you must do it explicitly:
let newModel = this.store.createRecord('post-following', {
user: user,
post: post
})
// since model.save() returns a promise
// we wait for a successfull save before
// re-setting the `model` property
newModel.save().then(() => {
this.set('model', newModel);
});
For a more clear design, I would also recommend that you create an alias to the model property that more specifically describes your model or override the default behavior of setupController if you are also doing some initial setup on the controller. So either:
export default Ember.Controller.extend({
// ...
blog: Ember.computed.alias('model') // more descriptive model name
// ...
});
Or:
export default Ember.Route.extend({
// ...
setupController(controller, resolvedModel) {
controller.set('blog', resolvedModel); // more descriptive model name
// do other setup
}
// ...
});
Your model is set when you enter the page. When changes are made, your model doesn't change. The only reason why the list is updated when you destroy the record is because it simply doesn't exist anymore. Reload the model after clicking the follow button or unfollow button, or manually change the values for the list/button.

How to get the 'keyword' in domain.com/keyword with Iron Router

I am working on a site where I have to search in the DB for string that come after the / on the root domain. I can't find anything about it in the documentation.
I am trying to make it work with Iron Router but any other suggestion would work out.
Thanks for the help!
Edit: Basically I just want to pass anything that comes after domain.com/ to a variable.
Here's something i've been doing so maybe it'll lead you down the right path
Route sends URL params to ownedGroupList template
Router.route('/users/:_id/groups', {
name: 'owned.group.list',
template: 'ownedGroupList',
data: function() {
return {params: this.params};
}
});
Template ownedGroupList can access params object using this.data in onCreated, onRendered, and onDestroyed template event handlers
Template.ownedGroupList.onCreated(function(){
this.subscribe("owned-groups", this.data.params._id );
});
Template ownedGroupList can access params through this variable in helper methods
Template.ownedGroupList.helpers({
groups: function() {
return Groups.find({owner: this.params._id });
}
});
Template ownedGroupList can access params through template.data variable in event handlers
Template.ownedGroupList.events({
'click .a-button': function(event, template) {
var group = Groups.findOne({owner: template.data.params._id });
// do something with group
}
});
Here's a simple route that should do the trick
Router.route('/:keyword', {
name: 'keyword',
template: 'keywordTemplate',
data: function() {
return this.params.keyword;
}
});
This will pass the keyword as the data context to your template and then you can do whatever you want with it. Alternatively you can perform the search straight in the router (especially if you're passing the keyword to a subscription so that the search runs on the server). For example:
Router.route('/:keyword', {
name: 'keyword',
template: 'keywordTemplate',
waitOn: function(){
return Meteor.subscribe('keywordSearch',keyword);
},
data: function() {
return MyCollection.find();
}
});
This second pattern will send your keyword to a subscription named keywordSearch that will execute on the server. When that subscription is ready, the route's data function will run and the data context passed to your keywordTemplate will be whatever documents and fields have been made available in MyCollection.

Categories

Resources