Pretty simple test app, but for some reason, the template is not rendering and so far I just try one template only. Only blank page showing. no error
// The Application
// ---------------
// Our overall **AppView** is the top-level piece of UI.
app.AppMainView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: '#nested-viewer',
view1Template: _.template( $('#view1').html() ),
view2Template: _.template( $('#view2').html() ),
view3Template: _.template( $('#view3').html() ),
// New
// Delegated events for creating new items, and clearing completed ones.
events: {
'keyup [nv-data="myinput"]': 'changedData',
},
// At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*.
initialize: function() {
console.log("init")
this.dataStorage1=new app.dataStorage();
console.log(this.dataStorage1)
// this.listenTo(app.Fund, 'change',this.adjustAllDivison);
},
// New
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
this.$el.html(this.view1Template());
},
changedData: function(){
console.log("changedData");
},
resetAllDivison: function(){
console.log("resetAllDivison")
},
});
// js/app.js
var app = app || {};
$(function() {
// Kick things off by creating the **App**.
new app.AppMainView();
});
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Nested View</title>
<link rel="stylesheet" href="src/app/style.css">
<link rel="stylesheet" href="/library/dragdealer/0.9.8/css/dragdealer.css">
</head>
<body>
<div id="nested-viewer">
</div>
<!-- Templates -->
<script type="text/template" id="view1">
<div class="view1s">
<input nv-data="myinput" type="text" id="input1" name="" value="123" placeholder="">
</div>
</script>
<script type="text/template" id="view2">
<div class="view2s">
<p id="display2">View 2 </p>
</div>
</script>
<script type="text/template" id="view3">
<div class="view3s">
<p id="display3">View 3</p>
</div>
</script>
<!-- Loading Templates + Vendor Scripts -->
<script type="text/template" id="item-template"></script>
<!-- Addons -->
<script src="/library/dragdealer/0.9.8/js/dragdealer.js"></script>
<!-- Main Framework -->
<script src="src/assets/lib/jquery.js"></script>
<script src="src/assets/lib/underscore.js"></script>
<script src="src/assets/lib/backbone.js"></script>
<script src="src/assets/lib/backbone.localStorage.js"></script>
<!-- Modules -->
<!-- Main -->
<!-- Nested View -->
<script src="src/app/modules/NestedView/models/dataStore.js"></script>
<script src="src/app/modules/NestedView/views/AppMainView.js"></script>
<!--
<script src="src/app/modules/NestedView/views/view1.js"></script>
<script src="src/app/modules/NestedView/views/view2.js"></script>
<script src="src/app/modules/NestedView/views/view3.js"></script>
-->
<!-- App Base -->
<script src="src/app/router.js"></script>
<script src="src/app/app.js"></script>
</body>
</html>
You actually don't append the View's el to DOM. You don't even call the view instance's render method. You could do it on initialization, i.e. in your initialize method or after creating the instance.
var mainView = new app.AppMainView();
mainView.render();
mainView.$el.appendTo(document.body);
Edit: I just noticed that you are passing a selector to the view (el: '#nested-viewer'). This means that just need to call the render method as the element exists in the DOM.
Related
I've inherited a project and am very green regarding UI. This project uses Bootstrap, nvd3, and flot on Chrome. There is a layout view in which jQuery is referenced, and then partial views for each page are rendered in the layout body. On a dashboard page, the graphs don't show up unless jQuery is again referenced in the scripts, but that reference causes the sidebar to cease working. Referencing easing can be duplicated in the dashboard scripts to get both the graphs to appear and the sidebar to function, but one graph still doesn't work properly. This leads me to believe that jQuery and its libraries are being referenced multiple times on the layout and partial views, wiping out the references that display graphs, activate the sidebar, render graphs correctly, etc.
If that's correct, is there a way to trace each jQuery reference? I've tried deleting multiple references in the source code by sight, moving layout references into the HTML body, testing what's being hit through Chrome Developer Tools, re-calling references as described above as a band-aid, and searching here for similar questions, but nothing seems to achieve both the correct visual and functionality. Also, can a duplicated jQuery reference on a different partial view that shares the same parent layout nullify references in any other partial view? Please opine if there's another possible solution not considered here, because I'm ultimately trying to get the sidebar and graphs working properly. Thanks in advance for looking at this.
Here's the layout with references:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>#ViewBag.Title</title>
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<link rel="shortcut icon" href="/favicon.ico" />
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/icons")
#Scripts.Render("~/bundles/modernizr")
#RenderSection("headcontent", required: false)
<!-- page specific stylesheets -->
<!-- nvd3 charts -->
<link rel="stylesheet" href="/Content/lib/novus-nvd3/nv.d3.min.css">
<!-- owl carousel -->
<link rel="stylesheet" href="/Content/lib/owl-carousel/owl.carousel.css">
<!-- google webfonts -->
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400&subset=latin-ext,latin' rel='stylesheet' type='text/css'>
<!-- datepicker -->
<link rel="stylesheet" href="/Content/lib/bootstrap-datepicker/css/datepicker3.css">
<!-- date range picker -->
<link rel="stylesheet" href="/Content/lib/bootstrap-daterangepicker/daterangepicker-bs3.css">
<!-- timepicker -->
<link rel="stylesheet" href="/Content/lib/bootstrap-timepicker/css/bootstrap-timepicker.min.css">
<!-- ion.rangeSlider -->
<link rel="stylesheet" href="/Content/lib/ion.rangeSlider/css/ion.rangeSlider.css">
<!-- bootstrap switches -->
<link href="/Content/lib/bootstrap-switch/build/css/bootstrap3/bootstrap-switch.css" rel="stylesheet">
<!-- 2col multiselect -->
<link href="/Content/lib/multi-select/css/multi-select.css" rel="stylesheet">
<!-- multiselect, tagging -->
<link rel="stylesheet" href="/Content/lib/select2/select2.css">
<!-- main stylesheet -->
<link href="/Content/css/style.css" rel="stylesheet" media="screen">
<!-- moment.js (date library) -->
<script src="/Content/lib/moment-js/moment.min.js"></script>
[styles omitted...]
</head>
<body>
[header omitted...]
<!-- main content -->
<div id="main_wrapper">
[messages omitted...]
#RenderBody()
</div>
<!-- side navigation -->
<nav id="side_nav">
#Html.Partial("~/Views/Shared/_SidebarLeft.cshtml")
</nav>
<!-- jQuery -->
<script src="/Content/js/jquery.min.js"></script>
<!-- easing -->
<script src="/Content/js/jquery.easing.1.3.min.js"></script>
<!-- bootstrap js plugins -->
<script src="/Content/bootstrap/js/bootstrap.min.js"></script>
<!-- top dropdown navigation -->
<script src="/Content/js/tinynav.js"></script>
<!-- perfect scrollbar -->
<script src="/Content/lib/perfect-scrollbar/min/perfect-scrollbar-0.4.8.with-mousewheel.min.js"></script>
<!-- common functions -->
<script src="/Content/js/tisa_common.js"></script>
#RenderSection("Scripts", required: false)
</body>
</html>
And here's the dashboard HTML:
#using Project.Models
#model DashboardViewModel
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="heading_b">Prices Chart</div>
<div class="panel-body">
<div id="nvd3_cumulativeLine" style="width: 100%; height: 300px">
<svg></svg>
</div>
</div>
</div>
</div>
</div>
</div>
Finally, here are the dashboard scripts, with removal of jQuery causing the chart to disappear, removal of easing causing the sidebar to cease pop-outs, and removal of both causing the chart to disappear but leaving sidebar functionality intact.
#section Scripts{
<!-- page specific plugins -->
<!-- jQuery DUPLICATE -->
<script src="/Content/js/jquery.min.js"></script>
<!-- easing DUPLICATE -->
<script src="/Content/js/jquery.easing.1.3.min.js"></script>
<!-- nvd3 charts -->
<script src="/Content/lib/d3/d3.min.js"></script>
<script src="/Content/lib/novus-nvd3/nv.d3.min.js"></script>
<!-- flot charts-->
<script src="/Content/lib/flot/jquery.flot.min.js"></script>
<script src="/Content/lib/flot/jquery.flot.pie.min.js"></script>
<script src="/Content/lib/flot/jquery.flot.resize.min.js"></script>
<script src="/Content/lib/flot/jquery.flot.tooltip.min.js"></script>
<!-- clndr -->
<script src="/Content/lib/underscore-js/underscore-min.js"></script>
<script src="/Content/lib/CLNDR/src/clndr.js"></script>
<!-- easy pie chart -->
<script src="/Content/lib/easy-pie-chart/dist/jquery.easypiechart.min.js"></script>
<!-- owl carousel -->
<script src="/Content/lib/owl-carousel/owl.carousel.min.js"></script>
<!-- dashboard graph functions -->
<script src="/Content/js/apps/tisa_dashboard.js"></script>
<script type="text/javascript">
function cumulativeTestData() {
var closes = JSON.parse('#Html.Raw(Json.Encode(Model.Coordinates))')
return [
{
key: "Prices",
values: closes
},
];
}
</script>
}
You are correct in thinking that there is a conflict when loading the same script multiple times. Only load each script one time.
I can see why trying to remove those scripts from the partial view caused your partial views to fail. You are not loading the scripts until after the partial view. They do not exist until after everything in your partial view has been loaded and executed.
In your layout, move the scripts to the header (preferred) or at least to a point before you pull in the partial view. Then in your partial view, make sure there are no references to scripts which have already been loaded.
In partial views I often use a script wrangler to load in scripts which may or may not have been dynamically loaded. Here is something you can use to attempt to load scripts. It checks to see if a script by the same name has already been loaded on the page (specifically in the header tag) and if it has, it does not attempt to load it again. It's not the prettiest, but it gets the job done.
mycode = function()
{
//Put all your custom javascript here.
//This will run when the scripts below have successfully been processed.
}
var headTag = document.getElementsByTagName("head")[0];
var initialScripts = ["/scripts/jquery-2.1.4.min.js",
"/scripts/jquery-ui.min.js",
"/scripts/jquery.timepicker.min.js"];
var neededScripts = [];
for (var z = 0; z < initialScripts.length; z++) {
if (!isScriptLoaded(initialScripts[z]))
neededScripts.push(initialScripts[z]);
}
if(neededScripts.length)
addScripts(neededScripts, headTag, function () { mycode(); delete mycode; }, 0);
else {
mycode(); delete mycode;
}
function addScripts(scriptsToLoad, loadTag, callback, i) {
if (i >= scriptsToLoad.length)
return;
var script = scriptsToLoad[i];
var scriptTag = document.createElement('script');
scriptTag.setAttribute('type', 'text/javascript');
scriptTag.setAttribute('src', script);
if (i >= (scriptsToLoad.length - 1)) {
scriptTag.onload = callback;
}
else {
scriptTag.onload = function () {
console.log("Added script file " + script);
addScripts(scriptsToLoad, loadTag, callback, i + 1);
}
}
loadTag.appendChild(scriptTag);
}
function isScriptLoaded(url) {
var tags = document.getElementsByTagName('script');
for (var i = tags.length; i--;) {
var existingName = tags[i].src.split('/');
existingName = existingName[existingName.length-1];
var newName = url.split('/');
newName = newName[newName.length-1];
if (existingName == newName) return true;
}
return false;
}
I am using AngularJS to display results of my API (my first attempt at AngularJS), and want to use Jquery to add some effects to the page.
The problem is, Jquery seems to load before Angular has time to add images and other elements to the page. This prevents the JQuery effects from working I have been through numerous answers and tutorials, which center around the following solutions, none of which have worked for me.
Another approach suggested was to put the JQuery into "directives", but how would I put the contents of 3 large javascript libraries into an AngularJS directive? Sorry, I'm new in Javascript!
Here are the unsuccessful attempts:
$(window).load(function() {
// load JQuery plugins
$.getScript("./js/plugins.all.min.js");
});
<!-- after Angular is loaded !-->
angular.element(document).ready(function () {
// load JQuery plugins
$.getScript("./js/plugins.all.min.js");
});
<!-- after Jquery-main is loaded !-->
$(document).ready(function() {
// load JQuery plugins
$.getScript("./js/plugins.all.min.js");
});
Here are the relevant extracts of my code:
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<title>MyWebpage</title>
<!-- Template includes !-->
<link media="all" rel="stylesheet" href="./css/slider-revolution.css">
<link media="all" rel="stylesheet" href="./css/all.css">
<link media="all" rel="stylesheet" href="./css/style.css" class="color">
</head>
<body ng-app=“myApp">
<div ui-view></div>
</body>
<!-- Application Dependencies -->
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/angular-ui-router/build/angular-ui-router.js"></script>
<!-- Template scripts !-->
<!-- Application Scripts -->
<script src="scripts/app.js"></script>
<script src="scripts/indexController.js"></script>
app.js :
...
state('index', {
url: '/',
templateUrl: '../views/indexView.html',
controller: 'IndexController as user'
...
indexView.js
...
<!— JQuery plugin gallery -->
<div class="gallery responsive">
<div class="mask" ng-if=“myStuff.banner">
<ul class="slideset">
<ul style="margin:0px; padding:0px">
<li class="slide" data-transition="slidedown" data-slotamount="10" data-masterspeed="300" data-thumb="" ng-repeat="banner in user.banner" width="300">
<! -- load a big ol’ picture !—>
<img ng-src="../../storage/img/{{banner.image.image_url}}">
<div class="caption text-box lfl lfl" data-x="-91" data-y="140" data-speed="300" data-start="800" data-easing="easeOutExpo">
<h1><span>{{banner.banner_title}}</span></h1>
<a class="more" href="{{banner.banner_link}}">READ MORE</a>
<div style="" class="tp-leftarrow tparrows default"></div>
<div style="" class="tp-rightarrow tparrows default"></div>
</div>
</li>
</ul>
</div>
</div>
...
indexController.js:
...
// gets all the data from my API, including image src
vm.getMyStuff = function() {
$http.get('http://localhost:8888/api/public/myapistuff).success(function(myStuff) {
vm.myStuff = myStuff;
}).error(function(error) {
vm.error = error;
});
}
}
})();
$(window).load(function() {
// load JQuery plugins
$.getScript("./js/plugins.all.min.js");
});
I am following this tutorial to integrate SignalR to my project http://venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/
So basically this is my View where I want to show my table.
#{
ViewBag.Title = "PatientInfo";
}
<h2>PatientInfo</h2>
<h3>#ViewBag.pName</h3>
<h5>#ViewBag.glucoseT</h5>
#if (Session["LogedUserFirstname"] != null)
{
<text>
<p>Welcome #Session["LogedUserFirstname"].ToString()</p>
</text>
#Html.ActionLink("Log Out", "Logout", "Home")
<div class="row">
<div class="col-md-12">
<div id="messagesTable"></div>
</div>
</div>
<script src="/Scripts/jquery.signalR-2.2.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/SignalR/Hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.dataHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
});
function getAllMessages() {
var tbl = $('#messagesTable');
$.ajax({
url: '/home/GetMessages',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
}).error(function () {
});
}
</script>
}
My project is running but the table doesn't appear at all. I started by pasting the view because I believe that the scripts are not executed in the first place; The Alert Message is NOT being shown even if I try to add one directly after
$(function () {
alert("I am an alert box!");
This is my Layout.cshtml file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div class="content-wrapper">
</div>
</header>
<div id="body">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© #DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="SignalR/Hubs"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#p_table").dataTable();
});
</script>
#RenderSection("scripts", required: false)
</body>
</html>
I am using Visual Studio 2012, MVC4.
Please Help..
Make sure you have placed all your script tags from the view inside the scripts section of the view:
#section scripts {
... your <script> tags come here
}
The reason why your alerts don't work is because you have directly put them inside the body of the view which gets rendered at the #RenderBody() call of the Layout. But as you can see it's only at the end of this Layout that we have references to the scripts such as jQuery and signalr.
Now they will appear at the proper location: #RenderSection("scripts", required: false).
By the way use the console window in your webbrowser to see potential script errors you might have. For example in your case it would display that jQuery is not defined error.
Another remark: don't include signalR script twice: right now you seem to have included jquery.signalR-2.2.0.js in your view and jquery.signalR-2.2.0.min.js in your Layout.
I'm trying to add animation when changing the content inside a my html using ng-inculde, but when ever i add ['ngAnimate'] in the declaration of the controller all of the content inside the main tag simply dissapear.
HTML:
<div ng-app="myApp">
<div ng-controller="firstCtrl">
<div id="wrapper">
<main ng-init="nav('data/table.html')">
<div ng-include="filePath">
</div>
</main>
</div>
</div>
</div>
JS:
var myApp = angular.module("myApp",['ngAnimate']);
myApp.controller ('firstCtrl', function($scope, PersonService){
$scope.users = PersonService.list();
$scope.saveUser = function () {
PersonService.save($scope.newuser);
$scope.newuser = {};
}
$scope.nav = function(path){
$scope.filePath = path;
}
})
this code wont work since im adding ['ngAnimate'] but if i'll delete it and keep the brackets empty the content will display. can someone tell me why and if its the correct way to get the animation when the content changes (table.html changes to a different file)
this is the header part incase needed:
<head lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular-sanitize.js"></script>
<script src="https://code.angularjs.org/1.2.6/angular-animate.js"></script>
<script src="js/angular.min.js"></script>
</head>
Give reference of angular-animate.min.js file in order to use 'ngAnimate' module. You have to give reference of this file after angular.min.js.
I'm trying to update the content of a div (#slide-content) on clicking certain navigation elements (h2.pagenav). The content structure is uniform, and each requested HTML document contains two such nav elements ('Previous','Next'). However, my listener only fires once—for click events on the initial nav button present at page load, and I don't understand why.
My understanding is that when using jQuery's append() function instead of html(), the appended content should be registered with the DOM and thus available for event listening. Lil' help?
The page structure is pretty simple:
The HTML
<?php require('common.php'); ?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Ethogram Lab</title>
<link rel="stylesheet" href="css/foundation.css"/>
<link rel="stylesheet" href="css/foundation-icons.css"/>
<link rel="stylesheet" href="css/app.css"/>
<script src="js/vendor/modernizr.js"></script>
</head>
<body>
<div id="slide-content">
<div class="slide">
<div class="row">
<div class="row">
<!---- content ---->
</div>
<div class="row">
<div class="small-4 small-centered columns">
<h2 data-link="slide_0" class="medium button expand text-center pagenav">Start <i class="fi-play"></i></h2>
</div>
</div>
</div>
</div>
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
<script src='js/app.js'></script>
</body>
</html>
The Javascript
And here is the relevant it of app.js
/**
* PAGE VARS
*/
var DS = '/';
var WEBROOT = "127.0.0.1"+DS+"ethogram"+DS;
var PHP = ".php";
/**
* DOM LISTENERS
*/
$(".pagenav").click(function() {
console.log("*** pagenav listener has fired");
var loc = $(this).attr('data-link');
var pageNum = loc.substr(-2) == "_" ? loc.substr(-1) : loc.substr(-2);
var URL = WEBROOT+"slides"+DS+loc+PHP;
$.get(URL, function(data) {
$("#slide-content").html('').append(data).fadeIn();
});
});
The ".on()" function should be used. ".live()" is deprecated.
.on() function
$("body").on("click", ".pagenav", function() {
// do something
});
You should use
$("body").on ("click",".pagenav",function(){
// Your code go here
})
This function will detect the items created programatically
See Documentation