Marionette events are not triggered on Route - marionette

Why Marionette events are not triggered when I access a URL?
When I access the URL it suppose to call the function API.goHome()
but it doesn't! I don't understand why?
Here is my Code:
App.js
var PatientPortal = new Marionette.Application();
PatientPortal.addRegions({
'headerRegion': '#header',
'bodyRegion': '#body',
'footerRegion': '#footer'
});
PatientPortal.on("before:start", function () {
console.log("Started");
});
PatientPortal.navigate = function (route, options) {
options || (options = {});
Backbone.history.navigate(route, options);
};
PatientPortal.getCurrentRoute = function () {
return Backbone.history.fragment
};
PatientPortal.on("start", function(){
if (Backbone.history) {
Backbone.history.start();
}
if(PatientPortal.getCurrentRoute() == ""){
PatientPortal.navigate('home');
}
});
PatientPortal.start();
and Router Code:
PatientPortal.module("Portal", function (Portal, PatientPortal, Backbone, Marionette, $, _) {
Portal.Router = Backbone.Marionette.AppRouter.extend({
controller: "API",
appRoutes: {
"": "goHome",
"home": "goHome"
}
});
var API = {
goHome: function () {
console.log("go home");
}
};
PatientPortal.on("home:route", function () {
console.log("OKOKOK")
API.goHome();
});
PatientPortal.addInitializer(function () {
new Portal.Router({
controller: API
});
});
});
and here a home page code:
<!DOCTYPE html>
<html>
<head>
<title>INSAH - Login Page</title>
</head>
<body>
<div id="header"></div>
<script src="./js/assets/provider/jquery/jquery-2.1.1.min.js"></script>
<script src="./js/assets/provider/underscore/underscore-min.js"></script>
<script src="./js/assets/provider/backbone/backbone-min.js"></script>
<script src="./js/assets/provider/backbone/backbone.babysitter.min.js"></script>
<script src="./js/assets/provider/backbone/backbone.wreqr.min.js"></script>
<script src="./js/assets/provider/marionette/backbone.marionette.min.js"></script>
<script src="./js/app.js"></script>
<script src="./js/routes/route.js"></script>
</body>
</html>
Thanks.

I figured out the problem, it was because of starting the backbone history, the AddInitializer functuion shoudl be as following:
PatientPortal.addInitializer(function () {
new Portal.Router({
controller: API
});
Backbone.history.start();
});
and we should remove this line from app.js:
Backbone.history.start();

Related

function won`t run in if statement (eventlistener && eventlistener) javascript

I'm trying to get an if statement going to get api results.
First I put eventlisteners(click) on my images and when they are BOTH clicked, the get-api-results function should run.
I know I asked something similar before but I got that one screwed up, with this I`m a little closer I think.
Here`s the code
import axios from 'axios';
const container = document.getElementById('container')
let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
let img2 = document.createElement("img2");
img2.src = "https://picsum.photos/200/300";
const imgCheck = img.addEventListener("click", function(e) {
console.log("check")
})
const img2Check = img2.addEventListener("click", function(e) {
console.log("ok")
})
img.onclick = function () {location.href = "http://localhost:1234/pageTwo.html";};
document.body.appendChild(img);
document.body.appendChild(img2);
if (imgCheck && img2Check){
async function fetchRecipeOne() {
try {
const result = await axios.get('https://api.spoonacular.com/recipes/complexSearch?query=pasta&maxFat=25&number=2&apiKey=0b4d29adff5f4b41908e8ef51329fc48', {
headers: {
"Content-Type": "application/json"
}
})
console.log(result);
} catch (e) {
console.error(e);
}}
fetchRecipeOne();
} else {
console.log('no results');
}
And the html pages
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Title</title>
</head>
<body>
<img ><img/>
<script type="module" src="app.js"></script>
</body>
</html>
And page 2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Title</title>
</head>
<body>
<img id="img2"><img/>
<script type="module" src="app.js"></script>
</body>
</html>
Again, I`m pretty new to this stuff so if can give me enough details to sort this out you would do me a big favour.
Thanks!
Tom
addEventListener() does not return anything.
Maybe you can create a variable and change it in the eventlistener, like so:
let imgCheck = false;
img.addEventListener("click", function(e) {
imgCheck = true;
});
let img2Check = false;
img2.addEventListener("click", function(e) {
img2Check = true;
});
Also you redirect the user when he click on img, reset the click so to say. Maybe delete that
And the where you define img2 you try to create an element with the name 'img2' which isn't a valid element.
So change:
let img2 = document.createElement("img2");
To:
let img2 = document.createElement("img");
Lastly you check is the user has clicked on both the images when the script runs, what you can do is set the if statement in the async function, and call the function when the user clicks on a img.
So it could look something like:
import axios from 'axios';
const container = document.getElementById('container')
let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
let img2 = document.createElement("img");
img2.src = "https://picsum.photos/200/300";
let imgCheck = false;
img.addEventListener("click", function(e) {
imgCheck = true;
fetchRecipeOne();
});
let img2Check = false;
img2.addEventListener("click", function(e) {
img2Check = true;
fetchRecipeOne();
});
document.body.appendChild(img);
document.body.appendChild(img2);
async function fetchRecipeOne() {
if (imgCheck && img2Check) {
try {
const result = await axios.get('https://api.spoonacular.com/recipes/complexSearch? query=pasta&maxFat=25&number=2&apiKey=0b4d29adff5f4b41908e8ef51329fc48', {
headers: {
"Content-Type": "application/json"
}
})
console.log(result);
} catch (e) {
console.error(e);
}
} else {
console.log('no results');
}
}

ReactJS + Flux: How to pass data attribute from HTML?

I'm using ReactJS(Flux) and Laravel framework. I need to pass a variable from blade template to React components. I'm trying to use data-x attribute.
My question are..
How can I get the data in React(or Flux architecture)?
Do you have the best practice to store the data in Flux. Is app.js the best place to do it?
Thanks,
index.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ReactJS</title>
</head>
<body>
<section id="react" data-domain="{{env("DOMAIN")}}"></section>
<script src="{{ elixir('js/bundle.js') }}"></script>
</body>
</html>
/app.js
var React = require('react');
var SampleApp = require('./components/SampleApp.react');
React.render(
<SampleApp />,
document.getElementById('react')
);
/components/SampleApp.react
var React = require('react');
var SampleApp = React.createClass({
render: function() {
return (
<div>
Hello
</div>
);
}
});
module.exports = SampleApp;
===================================================
Edit 1
I could pass data by using {this.props.domain}. Next step is how to store the data as Flux way.
/app.js
var React = require('react');
var SampleApp = require('./components/SampleApp.react');
var react = document.getElementById('react');
React.render(
<SampleApp domain={react.dataset.domain}/>,
react
);
/components/SampleApp.react
var React = require('react');
var SampleApp = React.createClass({
render: function() {
return (
<div>
Hello {this.props.domain}
</div>
);
}
});
module.exports = SampleApp;
===================================================
Edit 2
Fixed
/index.blade.php
/app.js
/components/SampleApp.react.js
/actions/SampleActionCreators.js
/constans/SampleConstants.js
/dispatcher/SampleAppDispatcher.js
/stores/SampleStore.js
index.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ReactJS</title>
</head>
<body>
<section id="react" data-domain="test.example.com"></section>
<script src="{{ elixir('js/bundle.js') }}"></script>
</body>
</html>
/app.js
var React = require('react');
var SampleApp = require('./components/SampleApp.react');
React.render(
<SampleApp />,
document.getElementById('react')
);
/components/SampleApp.react.js
var React = require('react');
var SampleActionCreators = require('../actions/SampleActionCreators');
var SampleStore = require('../stores/SampleStore');
function getSampleState() {
return {
domain: SampleStore.getDomain()
};
}
var SampleApp = React.createClass({
getInitialState: function() {
return getSampleState();
},
componentDidMount: function() {
SampleStore.addChangeListener(this._onChange);
var domain = document.querySelector('#react').dataset.domain;
SampleActionCreators.initData(domain);
},
componentWillUnmount: function() {
SampleStore.removeChangeListener(this._onChange);
},
render: function() {
return (
<div>
Hello {this.state.domain}
</div>
);
},
_onChange: function() {
this.setState(getSampleState());
}
});
module.exports = SampleApp;
/actions/SampleActionCreators.js
var SampleAppDispatcher = require('../dispatcher/SampleAppDispatcher');
var SampleConstants = require('../constants/SampleConstants');
var ActionTypes = SampleConstants.ActionTypes;
module.exports = {
initData: function(domain) {
SampleAppDispatcher.dispatch({
type: ActionTypes.SAMPLE_INIT_DATA,
domain: domain
});
},
};
/constans/SampleConstants.js
var keyMirror = require('keymirror');
module.exports = keyMirror({
ActionTypes: keyMirror({
SAMPLE_INIT_DATA: null
})
});
/dispatcher/SampleAppDispatcher.js
var Dispatcher = require('flux').Dispatcher;
module.exports = new Dispatcher();
/stores/SampleStore.js
var SampleAppDispatcher = require('../dispatcher/SampleAppDispatcher');
var SampleConstants = require('../constants/SampleConstants');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var CHANGE_EVENT = "change";
var _domain = "";
var SampleStore = assign({}, EventEmitter.prototype, {
getDomain: function() {
return _domain;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
});
SampleAppDispatcher.register(function(action) {
switch (action.actionType) {
case SampleConstants.SAMPLE_INIT_DATA:
_domain = action.domain;
SampleStore.emitChange();
break;
default:
// no op
}
});
module.exports = SampleStore;
Your second edit is "correct" Flux way, same one I used on several large scale projects.
More simpler, alternative approach would be to get domain in app.js and pass it to your SampleApp as prop. This requires for DOM from your blade template to be loaded before JS executes. Since you are already putting your JS on bottom you should be good but I added window.onload event just to make it sure.
var React = require('react');
var SampleApp = require('./components/SampleApp.react');
function getDomain() {
return document.getElementById('react').dataset.domain;
}
function initReact() {
var params = {
domain: getDomain()
};
React.render(
<SampleApp {...params} />,
document.getElementById('react')
);
}
window.onload = function() {
initReact();
};
Now you can use {this.props.domain} to access your domain value in SampleApp.reatc.js

Post with AngularJS doesn't work

I would like to send a post request to my API. It works with jQuery :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
url: "api.php?option=inscription",
data: {lol : "mess"}
});
</script>
But it doesn't with AngularJS :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
{{1+1}}
<script>
$http.post('api.php?option=inscription', {lol : "mess2"})
.success(function(){alert('cool');});
</script>
If someone can help me. Thank you !
UPDATE :
Thank for your answers, I wanted to simplify but it wasn't clear anymore. So with your help, this is my new code, and the problem is the same. The data in the backend is empty ;
frontend :
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<div ng-controller="MainCtrl"></div>
{{data}}
<script>
var app = angular.module('myApp', []);
app.service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
var back = $http.post(dataUrl, dataTobePosted);
back.success(function(data){
console.log(data);
return data;
}).error(function(data, status, headers, config) {
return status;
});
}
});
app.controller('MainCtrl', function($scope, $http, SomeService){
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
$scope.data = SomeService.readData(url, dataTobePosted);
}
$scope.readData('api.php?option=inscription');
});
</script>
</html>
For clarity, I am suggesting a simple implementation. However, further reading may needed in order to understand the behaviour precisely.
angular.module('myApp').service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
// read data;
return $http.post(dataUrl, dataTobePosted)
.then(function(res) {
return res.data;
}, function(res) {
return res;
}
}
return this;
});
angular.module('myApp').controller('MyController', function($scope, SomeService) {
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
SomeService.readData(url, dataTobePosted)
.then(function(res) {
$scope.data = res;
}, function(res) {
// Display error
}
}
$scope.readData('api.php?option=inscription');
}
Usage in the HTML page
<div ng-controller="MyController">
{{data}}
</div>
You're using AngularJS as if it's jQuery. It's not. AngularJS works with dependency injection, so you need to wrap your $http call inside a controller.
You should probably read up on AngularJS. A few useful links:
https://docs.angularjs.org/guide/introduction
https://docs.angularjs.org/guide/controller
https://docs.angularjs.org/guide/di
"Thinking in AngularJS" if I have a jQuery background?
My bad, my problem came from my backend in the php I just get my data with :
$data = json_decode(file_get_contents("php://input"));
and not with $_POST

auto refresh div mvc3 ASP.Net

In Home Created Index as on View and PartialView as ViewData
But Div is not getting refresh.
<script type="text/javascript">
$(document).ready(function () {
var refreshid = setInterval(function () {
alert("test");
$("#dynamictabs").load("/Home/Index/")
}, 9000);
$.ajaxSetup({ cache: false });
});
</script>
<div class="dynamictabs">
#Html.Partial("ViewData", #Model);
</div>
Try the following:
<script type="text/javascript">
$(document).ready(function () {
window.setInterval(function () {
var url = '#Url.Action("SomePartial", "Home")';
$('#dynamictabs').load(url)
}, 9000);
$.ajaxSetup({ cache: false });
});
</script>
<div class="dynamictabs">
#Html.Partial("SomePartial")
</div>
and then you will have a controller:
public class HomeController: Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SomePartial()
{
return PartialView();
}
}
and then you will have a SomePartial.cshtml:
#DateTime.Now
Could you explain more on what you are trying to do here, please? Based on your code I see you have set your interval to 9 seconds. And you are trying to load content from home/index into #dynamictabs. Is this element on the same page?

socket.io not working in Chrome

i'm trying the this simple socket.io example and it works in Safari (send/receive from both sides). However, in the Chrome the client receives messages but the server won't receive messages sent by the client
index.html
<!doctype html>
<html>
<head>
<title>web sockets</title>
<meta charset="utf-8">
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8888');
socket.on('news', function (data) {
console.log(data);
writeMessage(data);
socket.emit('my other event', { my: 'data' });
});
function writeMessage(msg) {
var msgArea = document.getElementById("msgArea");
if (typeof msg == "object") {
msgArea.innerHTML = msg.hello;
}
else {
msgArea.innerHTML = msg;
}
}
</script>
</head>
<body>
<div id="msgArea">
</div>
</body>
</html>
server.js
var app = require('http').createServer(handler)
, io = require('/usr/local/lib/node_modules/socket.io').listen(app)
, fs = require('fs')
app.listen(8888);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Am I missing something? Chrome is on v.19
You can use http://socket.io-test.com to see if the problem is with your browser/proxy or your code.

Resources