Session.set() upon route event in Meteor - javascript

I have this functionality associated with clicking a button:
'click .single-speaker-info a': function(ev, speaker){
ev.preventDefault();
Session.set('selectedDocId', this._id);
}
But I'd like it to happen upon hitting this route
Router.route('speaker', {
path:'/speakers/:_id',
template: 'speaker',
data: function(){
return Speakers.findOne(this.params._id);
},
//my attempted solution
selectedDocId: function(){
Session.set('selectedDocId', this._id);
}
});
But I can't find any documentation on how to execute a method on a route.
Here is the Template.helper Im using to get the property Im setting
Template.speaker.helpers({
editingDoc: function(){
return Speakers.findOne({_id: Session.get('selectedDocId')});
}
});

But I can't find any documentation on how to execute a method on a route.
Iron Router offers a number of hooks:
onRun <-- probably what you need
onRerun
onBeforeAction
onAfterAction
onStop

You could use Template.x.rendered, once the page is rendered, any code in that block will be executed. Of course this would not be in your router.
In your case:
Template.speaker.rendered = function() {
//Get data from router
var data = Router.current().data();
Session.set('selectedDocId', data._id);
}

Related

Session Set and Get in Meteor

I am trying to dynamically get and set a pageTitle for my sample Meteor app, ideally I'd like to use jQuery, but any other solution would be good too.
I am trying to do it the rough way by setting a session when a certain div class exists on the page, but it's not working for some reason.
Basically, I have this:
Template.layout.helpers({
pageTitle: function() { return Session.get('pageTitle'); }
});
And I want to do something like
if ($('section').hasClass('single')) {
Session.set('pageTitle', 'Post Page');
}
Any idea ho to make this work? thanks!
You need to call it in a controller or the templates rendered section like this:
Template.layout.helpers({
pageTitle: function() {
return Session.get('pageTitle');
}
});
// set when a page template renders
Template.posts.rendered = function() {
setPageTitle("Blog Posts");
};
// or with Iron Router on *every* route using some sort of variable
Router.onBeforeAction(function() {
var someDynamicValue = "FOO";
setPageTitle(someDynamicValue);
});
// or in an IronRouter Controller
PostsController = RouteController.extend({
onBeforeAction: function() {
setPageTitle("Blog Posts");
}
});
// helper function to set page title. puts a prefix in front of page, you
// could opt set a boolean to override that
function setPageTitle(titleName) {
var prefix = "My Site - ";
if ($('section').hasClass('single')) {
Session.set('pageTitle', prefix + titleName);
}
}
As #Kuba Wyrobek pointed out, I needed to use the Template.layout.rendered function.
Here's a snippet that works
Template.postsList.rendered = function(){
Session.set('pageTitle', 'Listing Page')
};

Ember.js - I want an Action event (on="") to trigger when there is a transition to a new Route

I want an Action event (on="") to trigger when there is a transition to a new Route.
I've seen the list of Action event handlers and closest I could find is attaching the action to the largest HTML element on the page and triggering it with 'Mousemove". This is a terribly flawed away of going about what I want to do.
So just to draw it out.
<div {{action 'displayEitherHtml1or2'}} class="largestDOMelement">
{{#if showHtml1}}
// html 1 inside
{{/if}}
{{#if showHtml2}}
// html 2 inside
{{/if}}
</div>
'/objects' is a list of objects and clicking one leads to 'object/somenumber'. The action should automatically trigger when I enter the 'object/somenumber' page.
UPDATE: I've taken the contents from the previous update and dumped them into my DocRoute, but nothing it being triggered when I transition to 'doc' through {{#link-to 'doc' this.docID}} {{docTitle}}{{/link-to}}
VpcYeoman.DocRoute = Ember.Route.extend(VpcYeoman.Authenticated,{
toggleLetterSwitch: false,
togglePermitSwitch: false,
activate: function () {
var docTemplateID = this.get('docTemplateID');
if ( docTemplateID == 2) {
this.set('toggleLetterSwitch', true);
this.set('togglePermitSwitch', false);
console.log('docTemplateID equals 2');
} else {
this.set('toggleLetterSwitch', false);
this.set('togglePermitSwitch', true);
}
}
});
UPDATE DOS: setDocID is set in the DocsController to 1. Here's the whole thing.
VpcYeoman.DocsController = Ember.ArrayController.extend({
tempDocId: 1,
actions: {
addDoc: function (params) {
var docTitle = this.get('docTitle');
var docTemplateID = 1;
var docTemplateID = this.get('tempDocId');
console.log(this.get('tempDocId'));
var store = this.store;
var current_object = this;
var doc = current_object.store.createRecord('doc', {
docTitle:docTitle,
docTemplateID:docTemplateID
});
doc.save();
return true;
},
setDocId: function (param) {
this.set('tempDocId', param);
console.log(this.get('tempDocId'))
},
}
});
As #fanta commented, it seems like you're looking for the activate hook within your Route. This gets called when you enter the route where you define it. If you want to call it on every transition, you might consider defining a base route for your application and extending that instead of Em.Route:
App.BaseRoute = Em.Route.extend(
activate: function () {
// Do your thing
}
);
App.YourRoutes = App.BaseRoute.extend()
It's possible that there's a more appropriate place/time to do this, but without knowing quite what your action does, this is probably the best guess.
ETA: Looking at your edit, you won't want all your routes to extend App.BaseRoute the way I did it above; you should probably just include that activate hook explicitly in the routes which need it.

Backbone and jQuery trigger / bind custom event not heard

I'm writing a backbone app within an ASP.NET MVC page, and I'm having a truly baffling (to me) problem with using two custom events.
So, the MVC View (Planning.cshtml) has a select control which triggers the Backbone router to fetch a model on change. This model takes a good 10 seconds or so to load, so I want to disable the select while it loads to prevent multiple requests. To do this, I'm having my router trigger two custom events: 'subview-loading' and 'subview-loading-complete', and having my MVC view listen for these events.
The problem I'm having is that the router can hear both events, but Planning.cshtml will only hear the 'subview-loading-complete' event, not the first event.
Planning.cshtml code:
$(document).ready(function () {
var router = new Router({
el: '#TermPlanningReport'
});
var $routerEl = $(router.el);
$routerEl.bind('subview-loading', function() {
console.log('Planning.cshtml heard subview-loading');
//disable control
});
$routerEl.bind('subview-loading-complete', function() {
console.log('Planning.cshtml heard subview-loading-complete');
//enable control
});
});
Router.viewTerm() - the route method loading the model:
viewTerm: function (term) {
var that = this,
termModel = new PlanningTerm({ term: term }),
$thisEl = $(that.el);
//for testing purposes, see if router can hear itself...
$thisEl.on('subview-loading', function() {
console.log('router heard subview-loading');
});
$thisEl.on('subview-loading-complete', function () {
console.log('router heard subview-loading-complete');
});
//trigger loading
$thisEl.trigger('subview-loading');
// fetch data for model
termModel.fetch({
success: function (model, response, options) {
$thisEl.trigger('subview-loading-complete');
//render a vew...
},
error: function (model, response, options) {
$thisEl.trigger('subview-loading-complete');
//render a view...
}
});
},
Finally, my console output:
router heard subview-loading
router heard subview-loading-complete
Planning.cshtml heard subview-loading-complete
The variables $routerEl and $thisEl are both returning the same element properly.

Running an ember controller function when route loads to set property that controls a checkbox

I have set up an ember checkbox:
{{view Ember.Checkbox checkedBinding='isChecked'}}
This checkbox is bound to this controller:
App.SettingsController = Ember.Controller.extend({
isChecked: false,
isItChecked: function(){
var me = this;
$.getJSON('ajax/checkIfUseLowRes.php', function(data){
//console.log(data);
//me.isChecked = data;
me.set('isChecked', data);
//console.log(me.isChecked);
})
},
sendSetting: function(){
var isChecked = this.isChecked;
//this.set('isChecked', !isChecked);
console.log(isChecked);
$.post('ajax/setLowRes.php', {useLowRes: isChecked});
App.nameSpace.set('needsRefresh', true);
}.observes('isChecked')
});
Essentially it is a checkbox which posts a setting, my problem is setting the original state of the checkbox. When I load the route, I want to have isItChecked() run to set the checkbox's original state.
Example:
1. I go in to settings, click the checkbox
2. I leave the site and come back to the settings page
Here is where I want the isItChecked() function to run to query the server and see if the setting is set
If it is set, the get request returns true, I want the checkbox to be checked, hence setting me.isChecked to data (true)
as of right now I can't figure out how to do this, can anyone help me?
I've tried setting it in my App.SettingsRoute's model, but that doesn't seem to be able to run the function in my controller.
Thanks.
JSBin:http://jsbin.com/ukuwiq/1/edit
One way to accomplish this is by using the route's setupController method.
App.SettingsRoute = Ember.Route.extend({
setupController: function(controller, model) {
$.getJSON('ajax/checkIfUseLowRes.php', function(data){
console.log('setting isChecked to: ', data);
controller.set('isChecked', data);
})
}
})
This should get the job done with the fewest changes to your existing code but does have some drawbacks and is not exactly the-ember-way. Probably it would make more sense to have a model object that represents your settings, move ajax code to that model object and use the route's model hook to trigger as needed. See ember-without-ember-data for an example of how that can work.
as Mike says, you can use 'setupController' or you could also use this:
App.SettingsRoute = Ember.Route.extend({
activate: function() {
this.controllerFor('settings').isItChecked();
}
})
Could you not just use the init function? e.g.
App.IndexController = Ember.ObjectController.extend({
init: function() {
console.log("function run");
},

Backbone.js - navigating to a route after the "click" event on a view

My "view" is set up as below. simple.
var ItemView = Backbone.View.extend({
tagName : "li",
events : {
"click" : "display"
},
display : function() {
//app.navigate('item'); // take me to my route!
}
});
And I have my router
var App = Backbone.Router.extend({
routes: {
"" : "index",
"item" : "view_item"
},
index: function() {
alert('hi!');
},
view_item: function() {
alert('bye!');
}
});
app = new App();
Backbone.history.start();
Now, when I click on ItemView, it should run "display" method and I want the display method to take me to the route I specified in routes "item".
Is this possible? I thought "navigate" function will work, but it doesn't. How could I achieve this?
display : function() {
app.navigate('item', true);
}
You need the second parameter set to true.
From the Backbone documentation:
navigaterouter.navigate(fragment, [triggerRoute])
Whenever you reach a point in your application that you'd like to save as a URL, call navigate in order to update the URL. If you wish to also call the route function, pass triggerRoute.
Or you can do it directly from html, if you're using "< a >" tag.
example:
Show Itens
It also works, I prefer this way when of course is possible.

Categories

Resources