Layout and Regions using require js, Backbone, Marionette and Underscore js - marionette

I am trying to get to grips with Backbone and Require JS using marionette for some of its excellent features. However I am finding a few issues with the app being available to render views in a template :
Here is my Js file :
define(
['jquery',
'bootstrap',
'backbone',
'marionette',
'jquery-ui',
'text!templates/admin/home.html',
'js/views/admin/sidebar',
'js/views/admin/mainContent'
],
function(
$,
Bootstrap,
Backbone,
Marionette,
JqueryUI,
ViewMainLayout,
ViewSidebarMenu,
ViewMainContent
) {
var TestApp = new Backbone.Marionette.Application();
TestApp.addInitializer(function(){
var layoutView = new AppLayoutView();
layoutView.render();
TestApp.appRegion.show(layoutView);
layoutView.menu.show(ViewSidebarMenu);
layoutView.content.show(ViewMainContent);
});
var AppLayoutView = Backbone.Marionette.Layout.extend({
template: "#layoutPage",
regions: {
menu: "#sideMenuBar",
content: "#MainContent"
}
});
TestApp.addRegions({
appRegion: "#homepage"
});
TestApp.start();
});
Here is my html file :
<div id="homepage"></div>
<script type="text/template" id="layoutPage">
<div id="sideMenuBar"> --- Loading Sidebar Menu --- </div>
<div id="MainContent"> --- Loading Content --- </div>
<div class="clearfix"> </div>
</script>
The browser console throws me the error:
Error: Could not find template: '#homepage' in backbone.js file.
Any idea what is causing this?

It's obvious what's causing your problem - backbone couldn't find #homepage in your html. I assume that when you say "Here is my html file" you are referring to your template (text!templates/admin/home.html) and not the html at the page loaded by the browser? If that's the case, then it's important to note that nowhere in your view do you load anything from your template into the DOM, and that's probably why Marionette can't find it.
There are a few approaches for how to do this in combination with requireJS, but I usually just load the template them directly into the DOM using jQuery like so:
$("body").after(ViewMainLayout)

Related

Vue.js | Crawlers are not able to follow v-for generated links

I have a small site which uses Laravel and Vue.js for rendering a list. You can view it here. It looks like the Google crawler cannot follow the links generated by v-for.
Google Search Console says: Not found: vergleichen/%7B%7B%20anbieter.slug%20%7D%7D and all onpage crawlers I know are failing crawling the links.
What am I doing wrong? Is there a workaround? Any help is appreciated ♥
Update
#Linus: Your assumption is correct, this is the content of my blade file and the JS looks like this:
var suche = new Vue({
el: '#suchen',
data: {
search: ''
}
});
So I have to create a new component in order to get this working?
Update
I switched to Hideseek. Problem "solved".
The google crawler parses your HTMl before Vue can replace {{anbieter.slug}}
You can extract the content of your #app element into a <template> element, which google should ignore, and set this element as the template for Vue.
This should make sure that Vue will first parse the template, insert it into the DOM, and afterwards, the crawler can parse the links.
Untested though.
Example:
var App = new Vue({
el: '#app',
template: '#main',
data() {
return {
test: 'Test'
}
}
})
HTML:
<div id="app">
<!-- nothing here, content will come from the <template> below. -->
</div>
<template id="main">
{{test}}
</template>
To support IE9, use <script type="x-template"> instead of <template>
fiddle: https://jsfiddle.net/Linusborg/an49og18/

Load image ansyncronously with angular http.get call

This may come off as a bit newb-ish, but I don't really know how to approach this.
Can anyone recommend me a way of delivering and image from a flask backend, after being called by an angular $http.get call?
Brief example of what I am trying to do.
//javascript code
myApp.controller('MyCtrl', function($scope, $http){
$http.get('/get_image/').success(function(data){
$scope.image = data;
});
});
#flask back end
#app.route('/get_image/', methods= ['GET', 'POST'])
def serve_image():
image_binary = get_image_binary() #returns a .png in raw bytes
return image_binary
<!-- html -->
<html ng-app= "myApp">
<div ng-controller= "MyCtrl">
{{ image }}
</div>
</html>
So as you can see, I am attempting to serve a raw-byte .png image from the flask backend, to the frontend.
I've tried something like this
<html>
<img src= "/get_image/">
</html>
But the trouble is, 'get_image_binary' takes a while to run, and the page loads before the image is ready to be served. I want the image to load asyncronously to the page, only when it is ready.
Again, I am sure there are many ways to do this, probably something built into angular itself, but it is sort of difficult to phrase this into a google-able search.
Can't speak to the flask stuff, but below is some AngularJS code.
This directive won't replace the source attribute until after Angular manipulates the DOM and the browser renders (AngularJS : $evalAsync vs $timeout).
HTML:
<div ng-controller="MyController">
<img lazy-load ll-src="http://i.imgur.com/WwPPm0p.jpg" />
</div>
JS:
angular.module('myApp', [])
.controller('MyController', function($scope) {})
.directive('lazyLoad', function($timeout) {
return {
restrict:'A',
scope: {},
link: function(scope, elem, attrs) {
$timeout(function(){ elem.attr('src', attrs.llSrc) });
},
}
});
Same code in a working JSFiddle

How to use AngularJS to lazy load content in a collapsible panel

I am building an application that uses the Bootstrap Collapse component to render a sequence of panels, all of which will initially be in the collapsed state.
Since the page may contain many such panels and each of them may contain a large amount of content, it seems appropriate to populate these panels on demand, by executing an AJAX call when the user expands any panel.
The dynamic content of the page (including the markup for the panels) is rendered using AngularJS, and I assume it's possible to configure Angular to bind to an event on the panel elements, that results in their content being lazy loaded when they expand.
Unfortunately, after looking at the AngularJS docs and the available tutorials, I can't see how best to tackle this. Can anyone throw any light on it?
Thanks in advance,
Tim
This is way old, but the question might still come up now and then. I now find this to be the most suitable solution without polluting your controllers:
(myDirective loading its content via AJAX right after its creation.)
<accordion>
<accordion-group
heading=""
ng-repeat="foo in bar"
ng-init="status = {load: false}"
ng-click="status.load = true">
<myDirective ng-if="status.load"></myDirective>
</accordion-group>
</accordion>
each element created by ng-repeat gets its own $scope, so clicking ab accordion-group will result in only the respective directive being loaded.
edit:
depending on latency and the size of the data that's to be lazy loaded, you might consider using ng-mouseover instead of ng-click. That way loading starts some 100ms before the user opens the accordion which can reduce 'sluggishness' of your UI. Obviously there's the downside of occasionally loading content of groups that are never actually clicked.
#Tim Coulter, I've created something following the idea of #Stewie.
It can definitely be improved, but I guess it's a good starting point.
I've created a small directive to bind the click event of the accordion's panel. When the click event is fired, I passed the panel template via the panel-template= attribute and it updates the main-template which is used inside the panel.
It makes reference to 2 html files (panel1.html and panel2.html) that contains the content of the each panel.
I would recommend to create a service to fetch these files via AJAX - just the way you wanted.
On the code below I created a service called dataService for this purpose and you should bind it to the click event - so files are loaded on demand when the user clicks on it.
Note the the mainTemplate is a common panel to all accordions, so when it changes the all the accordions will have the same content, BUT I am assuming you want to display only one panel at time, right ?!
Anyway as I said before the logic can be improved to fix these little 'gotchas', but I believe the core functionality is there to start with. :)
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<script>
var myApp = angular.module('myApp', []);
myApp.controller('AccordionDemoCtrl', ['$scope', 'dataService', function ($scope, dataService) {
$scope.oneAtATime = true;
$scope.mainTemplate = '';
$scope.groups = [
{
id: "001",
title: "Dynamic Group Header - 1",
content: "Dynamic Group Body - 1",
template: "panel1.html"
},
{
id: "002",
title: "Dynamic Group Header - 2",
content: "Dynamic Group Body - 2",
template: "panel2.html"
}
];
}]);
myApp.factory('dataService', [ '$http', function($http){
return {
getData: function() {
return // you AJAX content data here;
}
}
}]);
myApp.directive('accordionToggle', [function () {
return {
restrict: 'C',
scope: {
mainTemplate: '=',
panelTemplate: '#'
},
link: function (scope, element, iAttrs) {
element.bind('click', function(e){
scope.mainTemplate = scope.panelTemplate;
scope.$apply();
});
}
};
}]);
</script>
</head>
<body ng-controller="AccordionDemoCtrl">
<div class="accordion" id="accordionParent">
<div class="accordion-group" ng-repeat="group in groups" >
<div class="accordion-heading">
<a class="accordion-toggle" main-template="$parent.mainTemplate" panel-template="{{ group.template }}" data-toggle="collapse" data-parent="#accordionParent" href="#collapse{{ $parent.group.id }}">
Collapsible Group Item {{ $parent.group.id }}
</a>
</div>
<div id="collapse{{ group.id }}" class="accordion-body collapse">
<div class="accordion-inner">
<div class="include-example" ng-include="mainTemplate"></div>
</div>
</div>
</div>
</div>
</body>
</html>

Grails remoteLink ajax issue populating JQuery accordion

Following the simple example from Jquery: Accordion Example
Using a remoteLink function from grails (AJAX) the information is pulled back from the controller and sent back to the GSP, which works fine. I do however want this data to be placed within a Accordion container... click here for screenshot of current functionality.
(Event Create Page rendering form template) _form - GSP:
<g:remoteLink controller="event" action="showContacts" method="GET" update="divContactList">Show Contacts!</g:remoteLink>
<div id="divContactList">
<g:render template="contactListAjax" model="[contactList: contactList]" />
</div>
<script type="text/javascript">
$(document).ready(function()
{
alert("Checking if I'm ready :)");
$( "#accordion" ).accordion({
header: 'h3',
collapsible: true
});
});
</script>
_contactListAjax - GSP Template
<div id="accordion">
<g:each in="${contactList}" status = "i" var="contact">
<h3>${contact.contactForename}</h3>
<div><p>${contact.email}</p></div>
</g:each>
</div>
Not quite sure what I'm doing wrong here, as I'm encasing the data with the div with an id accordion, yet doesn't load. Please refer to screenshot link above to see what is currently happening.
UPDATE
Event (Standard Generated CRUD, only showing where the relivant imports are) create - GSP
<link rel="stylesheet" href="${resource(dir: 'css', file: 'jquery.ui.accordion.css')}"/>
<g:javascript src="jquery-1.7.1.min.js"></g:javascript>
<g:javascript src="jquery-ui.min.js"></g:javascript>
Try replacing:
$(function() {
$( "#accordion" ).accordion({
collapsible: true
});
})
with
$( "#accordion" ).accordion({
collapsible: true
});
Edit:
You can't use an <r:script /> tag after the request is finished. The server has already laid out all of the resources. Change it to a standard javascript tag. Also the inclusion of your javascript and css files should be elsewhere on the page.
I solved this... (well Hack & Slash for now... not the best, but only viable solution for now)
var whatever is the stored HTML generated by the AJAX and placed into the divContactList on the update function. The Accordion is deleted and then rebuilt (not the best approach I realise)
var whatever = $('#divContactList').html();
$('#accordion').append(whatever)
.accordion('destroy').accordion({
collapsible: true,
active: false
});

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