I am trying to create a basic app for creating and editing contact details - for the purposes of improving my JavaScript skills. For some reason I can't manage to pass variable data from one class to the next - I'm trying to implement something similar to an MVC just to get started before i move to backbone.js
Here's my code:
//App Model Class
var contactsAppModel =
{
contacts:contacts,
/* App Methods */
init: function()
{
var theDetails;
//initiate App - pull App data
$j.ajax({
type: "post",
url: "inc/contactsModel.php",
dataType: "html",
data: '',
beforeSend: function(url,data)
{
$j('#result').html('<img src="images/page-loader.gif" height="80px" width="80px">').fadeIn('slow');
},
success: function(data)
{
this.contacts = data;
return this.contacts;
}
});
//alert('From WithOut '+this.contacts);
}
};
//App Class
var contactsApp =
{
//App Properties
contactDetails:'',
/* App Methods */
init: function()
{
//populate App properties
this.contactDetails = contactsAppModel.contacts;
$j('#result').html('<p>Contact Details:</p>'+this.contactDetails).css({'border-color': 'red'}).fadeIn('slow');
alert('From contactsApp: '+this.contactDetails);
},
};
How can i access the contents of variable 'data' from the contactsAppModel inside of contactsApp class? I'm trying to implement and OO-based solution to running a Javascript powered App with AJAX - not a functional approach.
Maybe can put contactsAppModel.init(); on the first line of your contactsApp.init() method.
Related
I am developing a hybrid mobile app with Framework7. I finished the user interface successfully and now I want to add functionality to my app. My problem is the navigation from one .html to another.
At the user interface i did the navigation with links, like this:
LOGIN
Because of some checks I removed the whole href-tag and here I come to the problem, how can i do this linking in jQuery?
I tried a lot, also followed the public "Router JavaScript API" (https://v1.framework7.io/docs/router-api.html) but nothing worked well (NOTE: this is not my whole code, just the affected parts):
Attempt 1
var myApp = new Framework7 ({});
var mainView = myApp.views.add('.view-main');
var app = {
init: function () {
events.doClickFunctions();
},
login: {
success: function () {
//here should be the linking done
mainView.router.load('/homepage/');
}
}
};
Problem: "myApp.views.add is not a function"
Attempt 2
var myApp = new Framework7 ({});
var mainView = myApp.addView('.view-main');
var app = {
init: function () {
events.doClickFunctions();
},
login: {
success: function () {
//here should be the linking done
mainView.router.load('/homepage/');
}
}
};
Problem: "myApp.addView is not a function"
And i tried some other combinations, but nothing worked.
Furthermore, I made a workaround: If the checks are successful, the href attribute will be added with jQuery and a virtual click is made on the element. So the user experience is like i want it to, but I guess thats not how it is supposed to work?
Thank you in advance!
try this
var app = new Framework7({
id: 'io.framework7.testapp',
precompileTemplates: true, //
template7Pages: true,
root: '#app',
theme: theme,
cache: false ,/* disable caching */
data: function () {
},
methods: {
helloWorld: function () {
app.dialog.alert('Hello World!');
},
},
routes: routes,
vi: {
placementId: 'pltd4o7ibb9rc653x14',
}
});
app.views.main.router.navigate('/login/');
for routing to another Page in jq use this :
app.views.main.router.navigate('/login/');
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.
I am getting a nested JSON data from REST. Now I want to capture that value in a variable. Everything is working fine but I don't know how should I initialize that variable.
So here is my initialize method of Model.
initialize: function() {
var self = this;
if (!this.get('dropdownData')) {
this.set({
dropdownData: []
});
}
}
}
AJAX CALL:
fetchDropdown: function(data) {
var self = this;
var d = $.Deferred();
var dropdownRequest = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: this.urlRoot,
data: JSON.stringify(data)
});
dropdownRequest.done(function(data)
{
self.set({
dropdownData: data
});
console.log("JSON SUCCESS!! YAY!!");
d.resolve();
});
Now dropdownData should be initialized as dropdownData: {} or dropdownData: [] or I don't need to initialize it at all.
P.S: Logic wise code snippet is working. I just want to know what's the correct way to initialize the dropdownData in the initializefunction in BACKBONE MODEL
I would recommend avoiding initializing dropdownData in the initialize method entirely, instead utilizing model.defaults here. If you add the following to your model definition:
defaults: function () {
return {
dropdownData: []
};
},
...then you can remove all the code in the body of your initialize method. The result of this change will be that an instantiated model will either have the supplied value (at instantiation) for dropdownData or the model will default to the empty array specified.
Note that it's important to use the function version of defaults here. If you were to do this instead:
defaults: {
dropdownData: []
},
...then any instantiated model not supplied with a value for dropdownData would share a value for dropdownData. Every instance would refer to the exact same array.
I'm using generator-react-webpack to create a React web app. This web app relies on JSON feeds - one of which is hosted on a CDN that does not support JSONP and the CDN url is a subdomain of the webapp. Is there any way to return the JSON data from within the React Component?
Basic React Component:
var AppComponent = React.createClass({
loadData: function() {
jQuery.getJSON(jsonFile.json?callback=?)
.done(function(data) {
console.log(data);
}.bind(this));
},
render: function(){
return ( ... );
}
});
I've tried a few solutions, and have come to the conclusion that I need to define my own callback on the JSON file like so:
JSON:
handleData({
"data": "hello World"
})
Is there a way for the handleData callback to be defined in the react component, or the response accessed from the react component? Any thoughts as to how I can get this to work are much appreciated. Thanks!
This looks like an odd way to do things, especially the part where you're using jQuery. That's a client-side utility to overcome not knowing where everything is and not having direct access to your elements. It makes no sense to use it when you're using React weith Webpack for bundling: React already knows where everything is (using refs) and Webpack means you can just use regular universal Node modules for everything that you need to do.
I'd recommend using something like, using request or a similar universal fetch API:
// loadData.js
var request = require('request');
var loadData = function(urlYouNeed, handler) {
request(urlYouNeed, function(error, response, body) {
if (error) {
return handler(error, false);
}
// do anything processing you need on the body,
var data = process(body);
handler(false, data);
};
So: just a module you can require in any component you define with require('./loadData'). And then in your actual component you do this:
var loadData = require('./loadData');
var AppComponent = React.createClass({
getDefaultProps: function() {
return {
jsonURL: "cdn://whateverjson.json"
};
},
getInitialState: function() {
loadData(this.props.jsonURL, this.updateData);
return {
data: []
}
},
updateData: function(err, data) {
if (err) {
return console.error(err);
}
data = secondaryEnsureRightFormat(data);
this.setState({ data: data });
},
render: function(){
var actualThings = this.state.data.map((entry, pos) => {
return <Whatever content={entry} key={entry.dontUseThePosVariableUpThere}/>
});
return (
<div>
...
{actualThings}
...
</div>
);
}
});
Much cleaner.
If I understand correctly the question, you only have to change your loadData this way :
loadData: function() {
var c = this
jQuery.getJSON(jsonFile.json?callback=?)
.done(function(data) {
c.handleData(data)
});
},
handleData: function(data) {
/* Implement here the function to handle the data */
},
I've been trying to make a request to a NodeJS API. For the client, I am using the Mithril framework. I used their first example to make the request and obtain data:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://localhost:3000/store/all"});
}
};
var Component = {
controller: function() {
var stores = Model.getAll();
alert(stores); // The alert box shows exactly this: function (){return arguments.length&&(a=arguments[0]),a}
alert(stores()); // Alert box: undefined
},
view: function(controller) {
...
}
};
After running this I noticed through Chrome Developer Tools that the API is responding correctly with the following:
[{"name":"Mike"},{"name":"Zeza"}]
I can't find a way to obtain this data into the controller. They mentioned that using this method, the var may hold undefined until the request is completed, so I followed the next example by adding:
var stores = m.prop([]);
Before the model and changing the request to:
return m.request({method: "GET", url: "http://localhost:3000/store/all"}).then(stores);
I might be doing something wrong because I get the same result.
The objective is to get the data from the response and send it to the view to iterate.
Explanation:
m.request is a function, m.request.then() too, that is why "store" value is:
"function (){return arguments.length&&(a=arguments[0]),a}"
"stores()" is undefined, because you do an async ajax request, so you cannot get the result immediately, need to wait a bit. If you try to run "stores()" after some delay, your data will be there. That is why you basically need promises("then" feature). Function that is passed as a parameter of "then(param)" is executed when response is ready.
Working sample:
You can start playing with this sample, and implement what you need:
var Model = {
getAll: function() {
return m.request({method: "GET", url: "http://www.w3schools.com/angular/customers.php"});
}
};
var Component = {
controller: function() {
var records = Model.getAll();
return {
records: records
}
},
view: function(ctrl) {
return m("div", [
ctrl.records().records.map(function(record) {
return m("div", record.Name);
})
]);
}
};
m.mount(document.body, Component);
If you have more questions, feel free to ask here.