How to run KnockoutJs on local server(wamp) with PHP? - javascript

Am newbie in KnockoutJs, i tried all tutorials on its official website.
Now i want to run all the practical tutorial on my local machine, i have downloaded knockout-2.1.0.js.
I tried this code but its not working on local machine
index.php
---------
<!DOCTYPE html>
<html>
<head>
<title>Knockout</title>
<script src="js/knockout-2.1.0.js"></script>
<link rel="stylesheet" href="css/styles.css" />
<script>
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.myname= ko.observable("Frank");
this.myage= ko.observable("26");
this.mydetails= ko.computed(function() {
var x;
return this.myname() + ", and my age is " + this.myage() + 'yr. old.';
}, this);
this.capitalizeMyName = function() {
var currentVal = this.myname(); // Read the current value
this.myname(currentVal.toUpperCase()); // Write back a modified value
};
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
</head>
<body>
<p>New Application</p>
<!-- This is a *view* - HTML markup that defines the appearance of your UI -->
<p>My Name: <strong data-bind="text: myname"></strong></p>
<p>My Age: <strong data-bind="text: myage"></strong></p>
<p>My Name: <input data-bind="value: myname" /></p>
<p>My Age: <input data-bind="value: myage" /></p>
<p>Full Detalis: <strong>Hi, my name is <text data-bind="text: mydetails"></strong></p>
<button data-bind="click: capitalizeMyName">Go caps</button>
</body>
</html>
If Someone has knowledge or idea about this, then suggest me. Thanks!

http://code.jquery.com/jquery-1.7.2.min.js
you need to include Minified file : js/jquery-1.7.2.min.js
And put your viewmodel code between:
$(document).ready(function(){
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of
});

Related

trouble loading javascript on html page load from jquery .load()

Working on a personal project with a navigation bar. I am using jquery x.load() to load html pages into a specific div. The pages load correctly into the div. However, one of the is using a jquery flipswitch. I am trying to read the state of this flipswitch, to no prevail. I have a main javascript file that loads the individual pages, which is basically my x.load(). I have a working jquery script for reading the switch state, that works when placed directly into the developers console. I have attempted this code both inline in the individual page as well as my main javascript file. When I place it inside the individual page, it will at times cause a race condition to develop.
I am looking for any suggestions, advice, or direction on being able to read the status of the flipswitch from the individual pages.
The first section of code is my javascript file. The second section of code, is both my individual page, as well as my main html page that loads the individual html page, respectively.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm'),
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>
<html>
<head>
<title>
</title>
<link rel="stylesheet" href="apt.css">
</head>
<body>
<header class="page-header">
<div class="apartment-name">Carlson Casa</div>
<div class="data-top">
<ul class="top-data">
<li>Time</li>
<li>Outside Temp</li>
<li>Inside Temp</li>
<li>Menu<span></span></li>
</ul>
</div>
</header>
<main class="main-content">
<nav class="side-nav">
<ul>
<li>Apartment</li>
<li class="nav-label">Living Room</li>
<li>Alarm control</li>
<li>Chandelier</li>
<li class="nav-label">Bedroom</li>
<li>Lights</li>
<li>Alarm Clock</li>
</ul>
</nav>
<div class="content">
Controls go here
</div>
</main>
<script src="jquery-2.1.4.js"></script>
<script src="main.js"></script>
</body>
</html>
As you are using jQuery Mobile Flipswitch of type checkbox, you can get the status by checking the property checked. Here is a jQuery Mobile Flipswitch playground:
var cases = {false: "Unchecked", true: "Checked"};
function getStatus() {
$("#statusLeft").html(cases[$("#LeftSwitch").prop("checked")]);
$("#statusRight").html(cases[$("#RightSwitch").prop("checked")]);
}
$(document).on("change", "#LeftSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusLeft").html("Changed to "+cases[status]);
});
$(document).on("change", "#RightSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusRight").html("Changed to "+cases[status]);
});
function toggleLeft() {
var status = $("#LeftSwitch").prop("checked");
$("#LeftSwitch").prop("checked", !status).flipswitch("refresh");
}
function toggleRight() {
var status = $("#RightSwitch").prop("checked");
$("#RightSwitch").prop("checked", !status).flipswitch("refresh");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="content">
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<span id="statusLeft">Unchecked</span>
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
<span id="statusRight">Unchecked</span>
</form>
<button class="ui-btn" onclick="getStatus();">Get Status</button>
<button class="ui-btn" onclick="toggleLeft();">Toggle Left</button>
<button class="ui-btn" onclick="toggleRight();">Toggle Right</button>
</div>
</div>
</body>
</html>
By using the change event instead of click you will be notified of the flipswitch toggling also if you are setting the status in code.
Additional notes:
About what you are defining "race condition" i believe you are referring to one of the common mistakes when using jQuery Mobile, i.e. document.ready vs. page events. Please read this post here, and also take some time to read the whole story in deep in this great post of Omar here: jQuery Mobile “Page” Events – What, Why, Where, When & How? (you will find here some other useful posts about this topic).
Moreover: you are trying to update the flipswtches manually by setting the ui-flipswitch-active class by yourself, but i believe you will run into the problem of keeping the status and the ui consistent. So, you may better use the standard JQM way to set the flipswitch status by using flipswitch.refresh. There is already an example in my code snippet.
The last note: until you strongly need it - and you know how to versioning jQuery Mobile - please use the same version of these libraries in all your files, so in your case i believe the pair jQuery 2.1 + JQM 1.4.5 shall be just fine.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm');
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')});
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>

angular expressions do not work inside the controller scope

I am facing a strange problem with the below code..
whenever I remove the ng-controller="page" from the body tag, the expressions start getting evaluated. But on applying this controller on body tag, the expressions tend to get printed as text rather than being evaluated.
Below is my relevant code (Snippet):
<html ng-app="app">
<head>
<!-- links removed for brevity -->
<script>
var app = angular.module('app',[]);
app.controller('page',function($scope){
$scope.segment.name = 'asdf';
});
</script>
</head>
<body ng-controller="page" style="padding:0px;">
<!-- additional markup removed for brevity -->
<form class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Portal ID" ng-model="page.segment.name"/>
</div>
<button class="btn btn-default">Search {{page.segment.name}}</button>
</form>
</body>
</html>
I am possibly making some blunder in the above code as the below code which I wrote as proof of concept works well.
POC code (Snippet):
<html ng-app="app">
<head>
<!-- links removed for brevity -->
</head>
<body ng-controller="page">
<a>Name : {{page.segment.name}}</a>
<input type = "text" ng-model="page.segment.name"/>
</body>
<!-- links removed for brevity -->
<script>
var app = angular.module('app',[]);
app.controller('page',['$scope',function($scope){}]);
</script>
</html>
Kindly help
Thanks in advance..
You are probably getting an error in the console. I would guess it's something similar to "Cannot set property 'name' of undefined." What you are doing here is not valid:
$scope.segment.name = 'asdf';
You need to either do this:
$scope.segment = {};
$scope.segment.name = 'asdf';
Or this:
$scope.segment = { name: 'asdf' };
You have to create the segment object explicitly before you attempt to set properties on it.

Javascript function not running with no errors

here is my function which is put into its own file(Javascript/submitDate.js):
document.onload = function(){
function submitDate(){
var time = new Date();
var nowDate =time.toISOString().slice(0,-14);
document.getElementById("dateShow").value=nowDate;
}
submitDate();
}();
This ran fine before I joined the page with my index.(When I put all my javascript and page layout into one file)
Here is the page(projectMain.html) of the code:
<html>
<div id="container">
<header>
<h3>Entries close on the 10th of March</h3>
</header>
<section>
<aside onload="submitDate();">
Last submitted:
</br>
<input type="date" id="dateShow" readonly>
</aside>
</section>
No errors pop up and it just shows the date layout box as: mm/dd/yyyy
EDIT:
The folder has a capital J.
Edit 2.0:
Link to what is shown. Underneath the "last submitted" is the date function that is not working. : http://prntscr.com/60ie8k
Edit 3.0:
Here is my Index:
<html>
<head>
<title>Sample Template</title>
<link rel="stylesheet" language="text/css" href="CSS/stylesheet.css"/>
<script language="javascript" src="Javascript/AJAX.js"></script>
</head>
<body onload="javascript:changePage('home');">
<h1>Little Big Planet</h1>
<div class="menu">
<a onclick="javascript:changePage('home');">Home</a>
<a onclick="javascript:changePage('powerups');">Power Ups</a>
<a onclick="javascript:changePage('bots');">Sackbots</a>
<a onclick="javascript:changePage('costumes');">Costumes</a>
<a onclick="javascript:changePage('projectMain');">Form</a>
</div>
<br />
<div id="content">
</div>
<script type="text/javascript" src="Javascript/submitDate.js"></script>
</body>
</html>
The aside element doesn't have an onload attribute (or load event). Only elements that load external content (e.g. <img>) and the document itself (where the attribute lives on the <body> element) do.
Use a <script> element instead.
<aside>
Last submitted:
</br>
<input type="date" id="dateShow" readonly>
</aside>
<script>
submitDate();
</script>
Additionally, you say that the file lives at "javascript/submitDate.js" but you are loading src="Javascript/submitDate.js". The function won't be available to call if you are using a case-sensitive file system (as the URL will 404).
You have a capitol 'j' in JavaScript in your HTML.
<script type="text/javascript" src="Javascript/submitDate.js"></script>
Try loading the js when the document is loaded
JS file:
document.onload = function(){
function submitDate(){
var time = new Date();
var nowDate =time.toISOString().slice(0,-14);
document.getElementById("dateShow").value=nowDate;
}
submitDate();
}();
The aside in your html
<aside>
Last submitted:
</br>
<input type="date" id="dateShow" readonly>
</aside>
Link to js file in the bottom of your body
<script type="text/javascript" src="pathtojsfile"></script>
Here is a working Fiddle

How to move Knockout viewmodel outside html page

How can i move the javascript code that's using knockout outside the html file? I want to create a separate file where everything is handled (or as much as possible). Also the templating should still work. Thanks in advance!
EDIT: Changes made. I have added the require.js in my Scripts folder and made an app.js and viewmodel.js file. But this still won't work. Any help would be very much appreciated :)
EDIT2: Almost there, Rumesh Eranga gave the right answer with using require.js. I only have a little problem left with my binding. 'data-bind="text: $(item.name)"' won't show the name, only '[object Object]'.
EDIT3: SOLVED!
This is the HTML file:
<head>
<script type="text/javascript" data-main="Script/app.js" src="Scripts/require.js"></script>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="Scripts/jquery.tmpl.js"></script>
<script id="shoppingItemTemplate" type="text/html">
<li><span data-bind="text: item.name"></span></li>
</script>
<div id="ActiveShoppingList">
<h2>Shopping items</h2>
<div id="ActiveList">
<ul data-bind="template: {name:'shoppingItemTemplate', foreach: items, as:'item'}"></ul>
<button data-bind="click:addItem">Add item</button>
</div>
</div>
</body>
Here is my Script/app.js:
require(['knockout-3.2.0', 'viewmodel'], function(ko, viewmodel) {
ko.applyBindings(new viewmodel);
});
And here is my Script/viewmodel.js:
define(['knockout-3.2.0'], function(ko) {
return function viewmodel (){
this.items = ko.observableArray([new item("item1"), new item("item2")]);
this.addItem = function()
{
this.items.push(new item("new item"));
};
};
function item(name)
{
return { name: ko.observable(name) };
}
});
Use Asynchronous Module Definition (AMD) With RequireJs.
Good article on Require and knockout can be found here.
Quoting from the site.
HTML
<html>
<head>
<script type="text/javascript" data-main="scripts/init.js" src="scripts/require.js"></script>
</head>
<body>
<p>First name: <input data-bind="value: firstName" /></p>
<p>First name capitalized: <strong data-bind="text: firstNameCaps"></strong></p>
</body>
</html>
scope/init.js
require(['knockout-x.y.z', 'appViewModel', 'domReady!'], function(ko, appViewModel) {
ko.applyBindings(new appViewModel());
});
scripts/appViewModel.js
// Main viewmodel class
define(['knockout-x.y.z'], function(ko) {
return function appViewModel() {
this.firstName = ko.observable('Bert');
this.firstNameCaps = ko.pureComputed(function() {
return this.firstName().toUpperCase();
}, this);
};
});
According to the code snippet given above you can see that you can make your view model code separate from the html and even can be modularize which is much helpful.

Knockoutjs is not working

I am started learning knockoutjs and I have faced an error. The Aptana editor shows an error at the:
data-bind: ....
property of the tag complaining that it is a proprietary tag. I have made sure to include all the needed javascript files plus I have checked a prior question:knockoutjs template not working.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='jquery-1.8.2.min.js'></script>
<script src='jquery.tmpl.min.js' type='text/javascript'></script>
<script src='knockout-2.2.0.js' type='text/javascript'></script>
</head>
<body>
<script>
function AppViewModel() {
this.firstName = "Bert";
this.lastName = "Bertington";
}
ko.applyBindings(new AppViewModel());
</script>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
</body>
</html>
Even after ignoring Aptana and hoping that the browser will show it I still get nothing. I am using Firefox 16 but I also tried on IE 8 but to no avail.
Move your script tag underneath your markup.
<body>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<script>
function AppViewModel() {
this.firstName = "Bert";
this.lastName = "Bertington";
}
ko.applyBindings(new AppViewModel());
</script>
</body>

Categories