How to pass a parameter to another page in Backbone? - javascript

How to pass a parameter to another page in Backbone?
I used Backbone to navigate to group_edit.html, and i'd like to pass id to group_edit.html.
e.g
var routes = {};
routes[AD.page + '/edit/:_id'] = 'act_edit_group';
act_edit_group: function(id) {
var t = this;
t.navigate("#ajax/group_edit.html", {
trigger: true
});
}
But I can't get id in the group_edit.html.
Thanks.

This way.
routes: {
"test/:id":"home"
},
home: function(id) {
console.log(id);
// "1"
}
If you pass this url (localhost....#test/1 ), this route will be triggered
Hope it helps

Related

Using a Javascript Data

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.

Backbone view/template fails to load from REST

I have properly coded a simple REST api and several backbone models. My parent model is called Topic and child model called Questions.
I'm trying to call a get method on the REST api and display the received Topic object to the user in a presentable manner. I am receiving the json (can be seen in the network tab on Chrome), but it is not getting sent to the view correctly.
Model:
var Topic = Backbone.Model.extend({
urlRoot: ROOT + '/topic',
idAttribute: 'topicId',
initialize: function () {
this.questions = new Questions([], {parent: this});
},
toJSON: function () {
var json = Backbone.Model.prototype.toJSON.call(this);
json.questions = this.questions.toJSON();
return json;
}
});
var Topics = Backbone.Collection.extend({
model: Topic,
url: ROOT + 'topic',
parse: function (response) {
return response.results;
}
})
REST URL:
http://localhost/Project/index.php/rest/resource/topic/
Backbone View: This is where I think the error is...(console log below prints an empty object)
var TopicListView = Backbone.View.extend({
el: '.page',
render: function () {
var that = this;
var topics = new Topics();
topics.fetch({
success: function (topics) {
console.log(topics);
var template = _.template($('#topic-list-template').html(), {topics: topics.models});
that.$el.html(template);
}
})
}
});
Using the above functions:
var topic = new Topic();
topic.fetch();
topicListView = new TopicListView();
var Router = Backbone.Router.extend({
routes: {
"": "home"
}
});
var router = new Router;
// render topic list for 'home'
router.on('route:home', function () {
topicListView.render();
});
Edit: Solution: Overriding the parse function in the collection proved to be the error. I wonder why...
The argument topics in your success handler is shadowing the variable topics.
The argument contains the parsed JSON response, not the Backbone Collection. You don't need that, so you can remove the argument.
The reference to topics will now be to your Collection, so topics.models will have the value you expect.
topics.fetch({
success: function () { // argument removed here so `topics` is no longer shadowed
var template = _.template($('#topic-list-template').html(), { topics: topics.models });
that.$el.html(template);
}
})

Meteor Iron Router : custom id route

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});
}
});
});

ember-cli data returned empty using initializer

I have an app where we need to create an initializer that inject our global into all the route where our global is a function that load data from a JSON file and return the data.
global-variable.js
export function initialize(container, application) {
var systemSetting = {
systemJSON: function(){
return Ember.$.getJSON("system/system.json").then(function(data){
return data
});
}.property()
};
application.register('systemSetting:main', systemSetting, {instantiate: false});
application.inject('route', 'systemSetting', 'systemSetting:main');
}
export default {
name: 'global-variable',
initialize: initialize
};
index.js - route
export default Ember.Route.extend({
activate: function(){
var _settings = self.systemSetting.systemJSON;
console.log(_settings.test);
},
}
system.JSON
{
"test" : 100
}
the result of the console.log give me this
ComputedProperty {isDescriptor: true, _dependentKeys: Array[0], _suspended: undefined, _meta: undefined, _cacheable: true…}
I think it's because of the JSON is not loaded yet but after that I try to do something like this at route
index.js - route
activate: function(){
var self = this;
var run = Ember.run
run.later(function() {
var _settings = self.systemSetting.systemJSON;
console.log(_settings);
}, 1000);
},
but still give me the same log. Am I use wrong approach to this problem?
I finally found the answer. Because of what I want to call is from an initializer then one that I must do is to use .get and if I just using get then the one that I received is a promise and to get the actual data I must use .then
The code will look like this:
index.js - route
activate: function(){
this.get('systemSetting.systemJSON').then(function(data) {
console.log(data.test);
});
}

Pass an argument when routing through a view in backbone.js

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
}
});

Categories