Event onClick with React - events

I fool around with Reactjs and try launch this code
var Kaka = React.createClass({render() { return <div> Hell o forld </div> }})
var Application = React.createClass({
handle() {console.log("took took");},
render() {return <div><Kaka onClick = {this.handle} /></div>}
})
React.render(<Application />, document.getElementById('app'));
Example on Codepen
I disire that while click on component Kaka starting work function "handle" and this return consol.log. But it doesn't work.
My question is that, may an inner component use function which is function of external component? On my example an external component is Application, an inner component is Kaka, and a function which i want launch is handle.
Please, tell me why my snippet cod don't work. I think, i do not understand how a components interact between ourself. Sorry for my English.

You are passing {this.handle} as a property named onClick to the KaKa class - not actually adding a click handler to it.
You need to use this prop you are passing, something like this:
var Kaka = React.createClass({
render() {
return <div onClick={this.props.onClick}> Hell o forld </div> }})
}
});
Here's a functional codepen of this.

You are passing a prop called onClick to Kaka and then in Kaka, you are not calling that function anywhere... in Kaka change :
<div> Hell o forld </div>
to
<div onClick={this.props.onCLick}> Hell o forld </div>
then you should achieve the desired results

Related

laravel passing a variable to js file from a controller

I have a js file located in assets folder (not View). can i pass a varible from a controller?
In view file:
The Js is called like this
<canvas id="chart1" class="chart-canvas"></canvas>
</div>
It is not possible (in my point of view) to put a variable to external JS file. You can use data-... attributes and get values from html elements.
For example you can pass your PHP variable as a json encoded string variable in your controller.
$data['chart_info'] = json_encode($chart_info);
return view('your_view', $data);
Then put it in data-info like this.
<canvas id="chart1" class="chart-canvas" data-info="{{ $chart_info }}"></canvas>
And finally in JS, you can get the variable and decode (parse) it as following.
let canvas = document.getElementById('chart1');
let info = JSON.parse(canvas.dataset.id);
console.log(info);
You can put that part of the Javascript in the view and send the variable to the same view. For example, add a section in view:
#section('footer')
<script type="text/javascript">
</script>
#endsection
Do not forget that you should add #yield('footer') to the end of your layout view.
I don't like to mix javascript and PHP/Blade, it might be hard to read the code in the future... You could use a different approach, loading the chart with a async ajax request.
You will have to create a end-point that returns the data you need for your chart:
Your router:
Route::get('/chart/get-data', [ ControllerName::class, 'getChartData' ]);
Your controller method:
public function getChartData() {
$chartData = [];
// Your logic goes here
return $chardData;
}
In your javascript (using jquery) file there will be something like that:
function loadChartData() {
$.ajax({
'url': '/chart/get-data',
'method': 'GET'
})
.done((data) => {
// Load your chart here!!!
})
.fail(() => {
console.log("Could not load chart data");
});
}
Hope I helped ;)

use parse react query results as an html tag attribute

This is my first time asking a question so I am a true SO newbie. I am currently working on a mobile app and I am using Parse React and Ratchet to build it. I have read the React documentations on FB github and apparently do not understand all enough to solve some problems. One of my problems is using the results of a Parse Query in the observe function of the declared ParseComponent as a value of a rendered react component, which in turn attempts to render the passed value as HTML. Below is the parent object:
export default class CategoryPage extends ParseComponent
{
observe(props,state){
return{
category: new Parse.Query('BusinessCategory').equalTo("objectId", this.props.categoryId)
};
}
render() {
return (
<div>
<Header text={this.data.category.objectId} back="true"/>
<div className="content">
<BusinessList categoryId={this.data.category.objectId}/>
</div>
<NavBar />
</div>
);
}
};
Notice I am passing the objectId of the category found in the Query as a text attribute of the Header React component. I am expecting Header as a child to use the passed property as follows:
var Header = React.createClass({
render: function () {
return(
<header className="bar bar-nav">
<h1 className="title">{this.props.text}</h1>
</header>
);
}
});
However the h1 is not rendering anything! I am thinking that this.data.category.objectId is a string and therefore should be rendered in the h1 tag as a string.
I do appreciate your answers very much.

Ember event in one view update another?

I have a small extract from my Ember app here. My page contains a number of views each containing different data each with their own controllers.
I want a search field (in index view) to go in one view which should "talk" to the stationList controller to update the content of the stationList view. This doesn't work. I get an error: TypeError: this.get(...).search is not a function
The logging outputs the name of the contoller I've asked it to use: App.StationListController
I added a second search form inside on the StationList View. This one works just fine. The logging this time outputs a dump of the StationListController object. So I am guessing that the other search form, despite my code (in SearchFormView): controllerBinding : 'App.StationListController', is not correctly setting the controller.
So I guess my question is why not?
How can I route the change on the form field in the one view to call a funciton on another view's controller?
Here's my code:
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<div id="searchForm">search form view search:
{{#view App.SearchFormView}}
{{view App.StationSearchField}}
{{/view}}
</div>
<div id="stationList">{{render stationList}}</div>
</script>
<script type="text/x-handlebars" data-template-name="stationList">
station list view search: {{view App.StationSearchField}}
<ul>
<li>List</li>
<li>will</li>
<li>go</li>
<li>here</li>
</ul>
{{searchTerm}}
</script>
And
App = Ember.Application.create({})
App.SearchFormView = Ember.View.extend({
init : function()
{
console.log("SearchFormView init", this.get('controller'))
}
})
App.StationSearchField = Ember.TextField.extend({
keyUp: function(event) {
var searchTerm = this.value
console.log("value",searchTerm,this.get('controller'))
this.get('controller').search(searchTerm)
}
})
App.StationListController = Ember.ArrayController.extend({
content : [],
searchTerm : null,
search : function(term)
{
this.set("searchTerm",term)
console.log("searching",term)
}
});
Fiddle: http://jsfiddle.net/ianbale/8QbrK/14/
I think the controllerBinding stuff is from the older version, I don't think that works anymore.
You can use controllerFor on get('controller') in the StationSearchField.
this.get('controller').controllerFor('station_list').search(searchTerm)
But controllerFor is deprecated and may be removed. Depending on your application structure you use needs on the controller.
Another way which I am using, is to send a custom event from the View, which the Route then sends to the corresponding controller.
App.IndexRoute = Ember.Route.extend({
events: {
search: function(term) {
controller = this.controllerFor('station_list')
controller.search(term);
}
}
});
and dispatch a search event from view like so.
this.get('controller').send('search', searchTerm);
The advantage of this method is you dispatch the same event from multiple places and it would get handled in the same way.
Here's the updated jsfiddle.

window.onload does not work in AngularJS

This code in a simple HTML file works:
<script>
function load() {
alert("load event detected!");
}
window.onload = load;
</script>
However, if I put it into the index.html file of an AngularJS web app, it does not. Does anybody know why not?
Call your function with ng-init
var app = angular.module('app',[]);
app.controller('myController', function($scope){
$scope.load = function () {
alert("load event detected!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app'>
<div ng-controller='myController' ng-init='load()'></div>
</div>
I prefer putting this kind of code in the app.run() function of angular.
e.g.
angular
.module('testApp', ['someModule'])
.constant('aConstant', 'hi')
.config(function($rootProvider) {/*some routing here*/})
.run(['$window', function($window) {
$window.onload = function() {/*do your thing*/};
}]);
also check this nice post that depicts the order that some things happen in angular
AngularJS app.run() documentation?
the following should work:
jQuery(function(){ /** my window onload functions **/ })
since angular uses a subset of jquery anyways you also may include the real thing.
better yet:
Instead of using this, you may consider using the angular way of initialising things:
that would be: http://docs.angularjs.org/api/ng.directive:ngInit
< any ng-init="functionInController(something)"...
to make it invisible until init: http://docs.angularjs.org/api/ng.directive:ngCloak
< any ng-cloak .....
to initialise/customize whole parts: http://docs.angularjs.org/guide/directive
< any directive-name....
Try
angular.element($window).bind('load', function() {
});

Failure to trap dijit.Tree "onclick"

I've read several examples of handling onClick for dijit.Tree.. in particular this one seems to tell me all I need: dojo how to override dijit class method
However, for some reason my handler gets called when my page first loads, and never when I click on a tree node?
Here's the code:
<div dojoType="dijit.layout.ContentPane" title="Published Blueprints" minSize="20" style="width: 300px;" id="leftAccordion" region="leading" splitter="true">
<div id="blueprintTree" dojoType="dijit.Tree" store="" query="" label="Blueprints" openOnClick="false">
</div>
</div>
...and I then do this...
dojo.ready(function() {
var tree = dijit.byId("blueprintTree");
tree.connect(tree, "onClick", function(item) {
// my code here...
});
});
... the "my code here" part gets invoked when I start (in debug) my jsp, but never when i lock around on nodes...
Obviously I'm missing something simple?
Regards
Brian
Is it required to put the connect inside the dojo.ready()? Maybe that is why it is called on startup?
Looking at the dijit.Tree source, I saw that the onClick had two args
This is what I used in my case to successfully capture onClicks:
In the Tree constructor add openOnClick: false:
var tree = new dijit.Tree( {
model: myModel,
openOnClick: false,
etc...
Then in the same function where I create the tree using the programmatic approach
dojo.connect( tree,"onClick", function(/*dojo.data*/ item, /*TreeNode*/ nodeWidget){
//my code
});

Resources