Using a Javascript Data - javascript

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.

Related

How to maintain app wide data in knockoutjs+requirejs

In my project, I need to maintain a common data object for all the modules in the application.
This is where I store all the REST API's and the app wide data. (Something like store in react redux)
dataService.js
define(['jquery', 'app'], function($, app) {
var url = app.serviceURL;
function loginUser(data) {
data.type = "login";
return $.ajax({
url: url + '/authentication.php',
data: data,
method: "POST"
});
};
function logoutUser(data) {
data.type = "logout";
return $.ajax({
url: url + '/authentication.php',
data: data,
method: "POST"
});
};
return {
actions: {
loginUser: loginUser,
logoutUser: logoutUser
},
user: {
isLoggedIn: ''
}
}
});
I am requiring dataService.js file in ViewModel files to call login and logout services.
dataService.actions.loginUser(data)
.then(function(data) {
dataService.user.isLoggedIn = true; // I changed the app wide data here
}
});
My problem is, when I requiring the dataService in some other ViewModel, the value of dataService.user.isLoggedIn is set as default value. How can I preserve this as an app wide data?
It may be instantiating a new object for each module. You can create a global variable by doing:
document.dataService = new dataService();
Try using the above method. This might solve your problem.

page object: visit <page_url> in nightwatch.js

In Geb and WATIR there are certain keywords which we use to visit to the page_url which we have specified in page class. E.g. to keyword in Geb and visit keyword in WATIR.
What similar we can use in nightwatch.js. This is what I have tried but it gives error:
I have tried:
module.exports = {
url: function () {
return this.api.globals.launchUrl + "/goto/desiredPage.html";
},
commands: [pageCommands],
elements: {}
};
In page class I am using it as:
desiredPage
.url()
.foo()
.bar();
client.end();
but it is giving error .url is not a function.
You can see the nightwatch examples inside the nightwatch folder for example:
[page-objects/home.js]
var searchCommands = {
submit: function() {
this.waitForElementVisible('#submitButton', 3000)
.click('#submitButton')
.api.pause(1000);
return this; // Return page object for chaining
}
};
module.exports = {
url: 'http://google.com',
commands: [searchCommands],
elements: {
searchBar: { selector: 'input[name=q]' },
submitButton: { selector: 'button[type=submit]' }
}
};
and then in the test:
/* jshint expr: true */
module.exports = {
'Demo Google search test using page objects' : function (client) {
var homePage = client.page.home();
homePage.navigate();
homePage.expect.element('#searchBar').to.be.enabled;
homePage
.setValue('#searchBar', 'Nightwatch.js')
.submit();
var resultsPage = client.page.searchResults();
resultsPage.expect.element('#results').to.be.present.after(2000);
resultsPage.expect.element('#results').to.contain.text('Nightwatch.js');
resultsPage.expect.section('#menu').to.be.visible;
var menuSection = resultsPage.section.menu;
menuSection.expect.element('#web').to.be.visible;
menuSection.expect.element('#video').to.be.visible;
menuSection.expect.element('#images').to.be.visible;
menuSection.expect.element('#shopping').to.be.visible;
menuSection.productIsSelected('#web', function(result) {
this.assert.ok(result, 'Web results are shown by default on search results page');
});
client.end();
}
};
so "url()" command in pages does not exist you need to define the url in te page and the use "navigate()" instead.

How to pass a parameter to another page in Backbone?

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

Variable in Angular http jsonp config

I am using http.jsonp to make cross domain calls and everything works fine, My config object is as below:
var config = {
params: {
action: "query",
prop: "revisions",
format: "json",
rvlimit: 50,
titles: 'obama',//works
// titles: val, //doesn't works
callback: "JSON_CALLBACK"
}
};
var url = "http://en.wikipedia.org/w/api.php?";
$http.jsonp(url, config).success(function(data) {
var pages = data.query.pages;
for (var pageid in pages)
{
$scope.revisions = pages[pageid].revisions;
break; // expect only one page
}
$scope.loaded = true;
});
when the titles has a static value of obama, it works fine however I added an input box from where I am getting the value and I am trying to set the value of the input box to titles and load the particular feed, however it is not working. I have reproduced the issue on jsfiddle,
Any Ideas how to fix this/
http://jsfiddle.net/L4qZZ/
I assume you need to fetch the contents after the user hits the "Go" button.
The problem with your code is that you are using val to set the title instead of $scope.val.
If you update that and then correct the code to make the HTTP request when user clicks the button, your data is fetched as expected.
Fiddle that demonstrates the solution.
Just type "obama" into the input and click the button to get your data.
since you are not using $scope for getting the ng-model values, use $scope.val instead of val
Try this out
var config = {
params: {
action: "query",
prop: "revisions",
format: "json",
rvlimit: 50,
titles: $scope.val,
callback: "JSON_CALLBACK"
}
};
It's better to reorganize your code a little. Move data loading functionality into a service like this one:
app.factory('Wiki', function ($q, $http) {
return {
loadData: function (title) {
var deferred = $q.defer(),
config = {
params: {
action: "query",
prop: "revisions",
format: "json",
rvlimit: 50,
titles: title,
callback: "JSON_CALLBACK"
}
},
url = "http://en.wikipedia.org/w/api.php?";
$http.jsonp(url, config).success(function(data) {
var pages = data.query.pages;
for (var pageid in pages) {
deferred.resolve(pages[pageid].revisions);
break;
}
});
return deferred.promise;
}
};
});
And then you can use it like this in controller:
app.controller('HistoryController', function($scope, Wiki) {
$scope.loaded = false;
$scope.getData = function(val) {
Wiki.loadData(val).then(function(data) {
$scope.loaded = true;
$scope.revisions = data;
});
}
$scope.getData('obama');
});
Using services makes everything more flexible when you deal with data.
Demo: http://jsfiddle.net/L4qZZ/1/

Name space my backbone models

I currently set out my models like this:
var Contact = Backbone.Model.extend({
defaults: {
photo: "img/placeholder.png",
name: "",
address: "",
tel: "",
email: "",
type: ""
}
});
and my collection like so:
var Directory = Backbone.Collection.extend({
model: Contact
});
Then in my main app.js file, I'm doing this to define my routes:
var AppRouter = Backbone.Router.extend({
initialize:function () {
$('#header').html(new HeaderView().render().el);
},
routes: {
"filter/:type": "urlFilter"
},
urlFilter: function (type) {
directory.filterType = type;
directory.trigger("change:filterType");
},
});
I'm getting an error with the code below which tells me 'directory' is undefined.
directory.filterType = type;
directory.trigger("change:filterType");
In my view I new up the collection like so, this.collection = new Directory(contacts);
I'm pretty new to backbone and I'm not sure if Im doing things in the correct order, and that my collection doesn't exist at the time when I'm trying to do my filterType and Trigger or wether I have things completely wrong.
My code can be viewed here, http://dan.ms/backbone
Any pointers gratefully received.
The directory variable seems to be created in a callback to tpl.loadTemplates. The variable is not available in the scope where it's being accessed inside your router. One way to do it would be to pass directory to the AppRouter constructor as a parameter. In AppRouter's constructor, save it as a property, and access it in the urlFilter method via the current instance.
var AppRouter = Backbone.Router.extend({
initialize: function (options) {
this.directory = options.directory;
},
urlFilter: function (type) {
this.directory.set("filterType", type);
}
});
// Initialize with:
var directory = new DirectoryView;
var app = new AppRouter({ directory: directory });
Backbone.history.start();

Categories