I have the following Backbone.Route:
var CustomRoute = Backbone.Router.extend({
routes: {
"/search": "onChangeUrl"
},
onChangeUrl: function (query, page) {
// handle event
}
});
Backbone.history.start({pushState: true});
And the following url: http://www.mysite_.com/search?name=erik&age=34
How could I handle event on changing any query params?
You need define two routers, like so
var CustomRoute = Backbone.Router.extend({
routes: {
'search': 'onChangeUrl',
'search?*query': 'onChangeUrl'
},
onChangeUrl: function (query) {
// handle event
}
});
Example
Related
I am using Framework7.
In app.js I have these codes to specify routes.
var app = new Framework7({
root: '#app',
theme: 'ios',
tapHold: true,
view: {
stackPages: true,
},
// Create routes for all pages
routes: [
{
path: '/',
url: 'index.html',
},
{
path: '/single/',
url: 'pages/post.php?id=',
}
]
});
And I have this data
var getId = "";
$(".yaziaclass").click(function() {
var getId = this.id;
});
I want to use this data in route configuration.
url: 'pages/post.php?id='+getId
The problem is it doesn't see the id. I guess it's because of the click action.
I want to change the getId's value when an user click a post. And use it in route configuration codes.
How can I fix it?
Modifying the function written above to ES6.
let getId = "";
$(".yaziaclass").click(() => {
getId = this.id;
});
console.log(getId);
If you don't want to use ES6, then use the following:
var getId = "";
function handleClick(){
getId = this.id
}
$(".yaziaclass").click(handleClick.bind(this));
console.log(getId); // should have updated the global `getId` value
I would also suggest you to read about Global and Local scopes in Javascript.
I want to access a child route via url eg:https://my-app.com/dashboard/library. When i click this, Ember redirects me to https://my-app.com/dashboard and populates this route's model data correctly, but i want to go to https://my-app.com/dashboard/library, with its new model data.
From the other hand i can access https://my-app.com/login via url, that has no model data btw.
At environment.js i have locationType: "auto", and my router.js is like:
Router.map(function() {
this.route('login');
this.route('dashboard', function() {
this.route('child', {path: '/child/:child_id'});
this.route('library');
});
});
My Routes:
// Route: dashboard
import Ember from 'ember';
import RouteHistoryMixin from 'ember-route-history/mixins/routes/route-history';
export default Ember.Route.extend(RouteHistoryMixin, {
model: function() {
let userId = this.authentication.getPlayerId();
let actions = this.store.findAll('action');
return Ember.RSVP.hash({
actions: actions,
tasks: Ember.RSVP.all([actions]).then((actions) => {
return this.store.findAll('task')
}),
rank: this.store.findAll('rank')
});
},
afterModel: function(){
this.transitionTo('dashboard.index'); // needless
},
setupController(controller, model) {
this._super(...arguments);
Ember.set(controller, 'tasks', model.tasks);
Ember.set(controller, 'rank', model.rank);
}
// . . .
And
// Route: dashboard/library
import Route from '#ember/routing/route';
import Ember from 'ember';
import RouteHistoryMixin from 'ember-route-history/mixins/routes/route-history';
export default Route.extend(RouteHistoryMixin, {
complete: Ember.inject.service(),
queryParams: {
taskId: {}
},
model(params) {
if(params.taskId) {
return Ember.RSVP.hash({
article: this.store.query('article', { filter: '{"inSyllabus": true}'}),
task: this.store.query('task', { filter: '{"id": ' + params.taskId + '}'})
});
}
else {
return Ember.RSVP.hash({
article: this.store.query('article', { filter: '{"inSyllabus": true}'})
});
}
},
setupController(controller) {
this._super(...arguments);
if (controller.taskId)
this.store.findRecord('task', controller.taskId).then((task) => {
controller.set('libraryQueryParam', task.points);
// Notify Task completion
let payload = {
startDate: new Date(),
endDate: new Date(),
points: task.points,
entries: 1
};
// PUT HTTP COMMAND FOR PLAYER
let playerTask = this.store.createRecord('playTaskTest', payload);
playerTask.save();
});
}
// . . .
May be a configuration flag or a Router config issue ?
How can i access this child route via url or has something like that happened to any of you?
I think the issue is in the dashboard. at the afterModel hook:
afterModel: function(){
this.transitionTo('dashboard.index'); // needless
}
This part redirects to dashboard.index every time you call dashboard route. Remember dashboard.index is a child route same as child and library so you will never reach them.
Having a bit of trouble with iron router and passing in a custom id from a collection.
Some context: I have a collection of "groups" in which they all have their own special id other than the default _id that is auto generated. I am trying to make a route that is like
" localhost:3000/groups/:groupid "
so each group will have its own rendered template with the groups information.
HTML :
<template name="Group">
<h1>Group: {{groupName}}</h1>
</template>
CLIENTSIDE:
grabbing a groupid from a session...
I tested this and it works so its not an issue with grabbing it from the session but rather with the router
var groupid = Session.get('groupID');
Router.go('/groups/:_id',{_id: groupid})
ROUTER:
Router.route('/groups/:_id', function () {
this.render('Group', {
data: function () {
return GroupsList.findOne({_id: this.params._id});
}
});
});
This will render a route with groupid as the params instead of the actual number
UPDATE:
CLIENT
Router.go('/groups/'+ groupid);
ROUTER
Router.route('/groups/:groupid', function () {
this.render('Group', {
data: function () {
console.log(this.params.groupid)
console.log(GroupsList.findOne({groupID: this.params.groupid}))
return GroupsList.findOne({groupID: this.params.groupid});
}
});
});
This seems to get the route to work but it wont render the groupname in the template
From the Iron Router Guide:
Now that we're using named routes in Router.go you can also pass a
parameters object, query and hash fragment options.
Router.go('post.show', {_id: 1}, {query: 'q=s', hash: 'hashFrag'});
However when you call Router.go, you are not passing a route name, but a url.
Try this:
Router.go('/groups/' + groupid);
Router.route('/groups/:_id', function () {
this.render('Group', {
data: function () {
return GroupsList.findOne({groupid: this.params._id});
}
});
});
On a side note from the answer just in case anyone else has this issue , I actually figured out there was an issue in the data type of the "this.params._id" , it seems it was coming up as a data type that was not a string or number and therefore could not be successfully used in the findOne method. In the end I just had to parseInt and this was the solution at the end :
Router.go('/groups/'+ groupid);
Router.route('/groups/:groupid', function () {
this.render('Group', {
data: function () {
var id = parseInt(this.params.groupid)
return GroupsList.findOne({groupID: id});
}
});
});
I want to pass an argument when routing in a Backbone.js application
Here is the transcript
var AppRouter = Backbone.Router.extend({
routes: {
'toolSettings/(:action)' : 'toolSettings'
}
});
var initialize = function() {
var app_router = new AppRouter;
app_router.on('route:toolSettings', function(actions) {
toolSettingsRoute.route();
});
Backbone.history.start();
};
On the UI I've a <a href="toolSettings/target" /> link which would invoke the toolSettingsRoute.route().
I want pass this action argument in the route method and i've to pass it to further proceedings.
I tried toolSettingsRoute.route(action) and it's not giving any error, though how do i use this argument in the toolSettingsRoute.js file
I'd like to know how we can pass arguments correctly and utilize them in the subsequent js
One options is to define your route functions in your router and you can just pass the parameter in to that function:
var AppRouter = Backbone.Router.extend({
routes: {
'toolSettings/(:action)': 'toolSettings'
},
toolSettings: function (action) {
// whatever
}
});
E X A M P L E
http://jsfiddle.net/mreis1/Nt9tm/1/
var AppRouter = Backbone.Router.extend({
routes: {
'toolSettings/:action' : 'toolSettings'
},
toolSettings:function (action){
//do whatever you want to do with the action parameter
}
});
I've got a router defined as such:
var MyRouter = Backbone.Router.extend({
routes: {
// catch-all for undefined routes
"*notfound" : "notFound",
},
initialize: function(options) {
this.route("my_resource/clear_filters", 'clearFilters');
this.route("my_resource/:id", 'show');
},
show: function(id){
console.log('show', id);
},
clearFilters: function() {
console.log('clearFilters');
},
notFound: function() {
console.log('notFound');
},
});
var app = {};
app.MyRouter = new MyRouter();
Backbone.history.start({silent: true});
Thus the following URLs would map as:
var opts = {trigger: true};
app.MyRouter.navigate('/foo', opts); // logged -> 'notFound'
app.MyRouter.navigate('/my_resource/123', opts); // logged -> 'show', '123'
app.MyRouter.navigate('/my_resource/clear_filters', opts); // logged -> 'clearFilters'
app.MyRouter.navigate('/my_resource/some_thing', opts); // logged -> 'show', 'some_thing'
How can I restrict the my_resource/:id route to only match on numeric parameters so that app.MyRouter.navigate('/my_resource/some_thing') is handled by notFound?
From the fine manual:
route router.route(route, name, [callback])
Manually create a route for the router, The route argument may be a routing string or regular expression. Each matching capture from the route or regular expression will be passed as an argument to the callback.
So you can always say things like:
this.route(/my_resource\/(\d+)/, 'show')
in your router's initialize if you need finer grained control over the routes than Backbone's string patterns give you.