Ember event in one view update another? - events

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.

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

Grails Render Partial Template to Div

I have a form page where the user selects a filter and a table on the bottom of the page updates. Each line in the table has a hyperlink in column one that associates a line item to an item in the database. I am not using GORM.
I need to be able to send the current filters to the controller via AJAX (functioning). Then I need to render a partial template (to a div) that loads the data created by a query based on the client's request parameters.
GSP:
....
<button onClick="generate_table()" class="pure-button">Generate Table</button>
...
<div id="selection_table">This should load with data</div>
...
JS:
//Link for AJAX
var url = "${g.createLink(action:'generate_table', controller: "statusReports")}";
//The actual call
$.getJSON(url, {
period: JSON.stringify($("#period").val()),
...
...
}, function(data) {
$('#selection_table').empty();
}).done(function(data) {
//I need to load the template at this point?
})
Controller:
def generate_table(){
def table_data = statusReportsService.generate_titles(params)
// Table data is already a map
// What do I need to render here? The template is named _selectionTable.gsp and should use table_data to generate html.
}
Partial:
I still haven't written the code for this yet. For now it is just some random text to see if I can even load the template when I press the button
In your controller:
render(template: 'selectionTable', model: table_data)
In your GSP/HTML you need to use $.get and use the following:
$('#selection_table').html(data)
That should do the trick!

Ember.js - child nested views' controller

I'm building a simple calendar app with Ember. My views are nested this way :
<script type="text/x-handlebars" data-template-name="calendar">
{{content.monthAsString}}
{{#each day in content.days}}
{{view App.DayView contentBinding="day"}}
{{/each}}
</script>
<script type="text/x-handlebars" data-template-name'="calendarDay">
{{content.date}}
</script>
My JS code :
App.CalendarController = Ember.ObjectController.extend({
content:App.Calendar.create(...);
oneDayHover:function(day){
}
});
App.CalendarView = Ember.View.extend({
templateName:"calendar"
});
App.CalendarDayController = Ember.ObjectController.extend({
dayHOver:function(){
//???? HOW TO ACCESS CalendarController?????
}
});
App.CalendarDayView = Ember.View.extend({
templateName:"calendarDay",
init:function(){
this._super();
this.set('controller', App.CalendarDayController.create());
},
mouseEnter:function(){
this.get('controller').dayHover();
}
});
Problem 1:
Isn't there a nicer solution than to override the init method of the view to set it's controller?
Problem 2:
How can I access the oneDayHover of CalendarController from the CalendarDayController?
Thanks in advance for the help
Update 1:
I should remark that those controllers exists in the same state. The point of the mouseenter is to display a popup on top of the CalendarDayView containing extra information.
1 - Do not assign Controllers to Views manually. Let Ember do the heavy Lifting! Have a look at Embers Router API / how to define routes. Routes will connect controllers and views and render them (Doc).
2 - If you follow point 1, your other problem will get easy with Embers way of dependency injection:
App.CalendarDayController = Ember.ObjectController.extend({
needs : ["calendar"],
dayHOver:function(){
//Access the single instance of CalendarController
var calendarController = this.get("controllers.calendar");
}
});
Update in response to Comment:
The CalendarRoute is created implicitly. Therefore all you would need to do, is modifying your template, i guess:
<script type="text/x-handlebars" data-template-name="calendar">
{{content.monthAsString}}
{{#each day in content.days}}
{{control "calendarDay" day}}
{{/each}}
</script>
As you see, i am suggesting the use of the {{control}} helper. What the code above basically says is :
"Dear Ember, please use the name 'calendarDay' to lookup
App.CalendarView and App.CalendarDayController and use them to render
the object day"
Additionally you have to tell ember, that it should not use the controller as singleton (which is the defaul behaviour):
App.register('controller:calendarDay', App.CalendarDayController, {singleton: false });
Note: I have not yet used the control helper myself, but this should be the way it works.

twitter bootstrap dynamic carousel

I'd like to use bootstrap's carousel to dynamically scroll through content (for example, search results). So, I don't know how many pages of content there will be, and I don't want to fetch a subsequent page unless the user clicks on the next button.
I looked at this question: Carousel with dynamic content, but I don't think the answer applies because it appears to suggest loading all content (images in that case) from a DB server side and returns everything as static content.
My best guess is to intercept the click event on the button press, make the ajax call for the next page of search results, dynamically update the page when the ajax call returns, then generate a slide event for the carousel. But none of this is really discussed or documented on the bootstrap pages. Any ideas welcome.
If you (or anyone else) is still looking for a solution on this, I will share the solution I discovered for loading content via AJAX into the Bootstrap Carousel..
The solution turned out to be a little tricky since there is no way to easily determine the current slide of the carousel. With some data attributes I was able to handle the .slid event (as you suggested) and then load content from another url using jQuery $.load()..
$('#myCarousel').carousel({
interval:false // remove interval for manual sliding
});
// when the carousel slides, load the ajax content
$('#myCarousel').on('slid', function (e) {
// get index of currently active item
var idx = $('#myCarousel .item.active').index();
var url = $('.item.active').data('url');
// ajax load from data-url
$('.item').html("wait...");
$('.item').load(url,function(result){
$('#myCarousel').carousel(idx);
});
});
// load first slide
$('[data-slide-number=0]').load($('[data-slide-number=0]').data('url'),function(result){
$('#myCarousel').carousel(0);
});
Demo on Bootply
I combined #Zim's answer with Bootstrap 4. I hope it will help someone.
First, load just the path of the images:
<div id="carousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item" data-url="/image/1.png"></div>
<div class="carousel-item" data-url="/image/2.png"></div>
<div class="carousel-item" data-url="/image/3.png"></div>
</div>
</div>
Then in JavaScript:
$('document').ready(function () {
const loadCarouselImage = function ($el) {
let url = $el.data('url');
$el.html(function () {
let $img = $('<img />', {
'src': url
});
$img.addClass('d-block w-100');
return $img;
});
);
const init = function () {
let $firstCarousel = $('#carousel .carousel-item:first');
loadCarouselImage($firstCarousel);
$firstCarousel.addClass('active');
$('#productsCarousel').carousel({
interval: 5000
});
};
$('#carousel').on('slid.bs.carousel', function () {
loadCarouselImage($('#carousel .carousel-item.active'));
});
init();
});

Using Jquery in Controller Page-ASP.NET MVC-3

Could any one give an example, how to use Jquery in Controller Page. MVC3 -ASP.NET(How To put various tags like )
I want to show a simple alert before rendering a view in Controller.
Thank you.
Hari Gillala
Normally scripts are part of the views. Controllers shouldn't be tied to javascript. So inside a view you use the <script> tag where you put javascript. So for example if you wanted to show an alert just before rendering a view you could put the following in the <head> section of this view:
<script type="text/javascript">
alert('simple alert');
</script>
As far as jQuery is concerned, it usually is used to manipulate the DOM so you would wrap all DOM manipulation functions in a document.ready (unless you include this script tag at the end, just before closing the <body>):
<script type="text/javascript">
$(function() {
// ... put your jQuery code here
});
</script>
If you are talking about rendering partial views with AJAX that's another matter. You could have a link on some page that is pointing to a controller action:
#Html.ActionLink("click me", "someAction", null, new { id = "mylink" })
and a div container somewhere on the page:
<div id="result"></div>
Now you could unobtrusively AJAXify this link and inject the resulting HTML into the div:
$(function() {
$('#mylink').click(function() {
$('#result').load(this.href, function() {
alert('AJAX request finished => displaying results in the div');
});
return false;
});
});

Resources