creating a toggle button to change page views - javascript

I am using knockout js to get my data to display and i am also using it to bind templates. I have a page that displays the same information in two different ways: one is a grid view and the other is a list view. Currently i have both views displayed on the page load. I would like to create two buttons one for the grid and one for the list. I am not sure how to go about it with Knockout js any tips or help is appreciated.
View Page
<div data-bind="template: {name:'grid-template'}, visible: !showList()"></div>
<div data-bind="template: {name:'list-template'}, visible: showList()"></div>
<input type="button" value="Toggle" data-bind="click: toggleView"/>
<script style="float:left" type="text/html" id ="grid-template">
<section " style="width:100%; float:left">
<section id="users" data-bind="foreach: Users">
<div id="nameImage">
<figure id="content">
<img width="158" height="158" alt="Gravatar" data-bind="attr:{src: GravatarUrl}"/>
<figcaption>
<a title="Email" id="emailIcon" class="icon-envelope icon-white" data-bind="attr:{'href':'mailto:' + Email()}"></a>
<a title="Profile" id="profileIcon" class="icon-user icon-white"></a>
</figcaption>
</figure>
<p data-bind="text:Name"></p>
</div>
</section>
</section>
</script>
<script style="float:left" type="text/html" id="list-template">
<div data-bind="foreach: Users">
<div style="width:60%; float:left; margin:10px; height:58px">
<img style="float:left; margin-right:5px" width="58" height="58" alt="Gravatar" data-bind="attr:{src: GravatarUrl}"/>
<p style="height:58px; float:left; vertical-align:central" data-bind="text:Name"></p>
<a style="float:right" title="Profile" class="icon-user icon-black"></a>
<a style="float:right" title="Email" class="icon-envelope icon-black" data-bind="attr:{'href':'mailto:' + Email()}"></a>
</div>
</div>
</script>
#section scripts{
#Scripts.Render("~/bundles/user" + ViewBag.Layout.AppVersionForUrls)
<script type="text/javascript">
(function ($) {
$.views.User.GetUser('#url');
})(jQuery);
</script>
}
Knockout JS
$.views.User.UserViewModel = function (data) {
var self = this;
self.Name = ko.observable(data.Name);
self.Email = ko.observable(data.Email);
self.ContentRole = ko.observable(data.ContentRole);
self.MD5Email = ko.observable(data.MD5Email);
self.GravatarUrl = ko.computed(function () {
return 'http://www.gravatar.com/avatar/' + self.MD5Email() + '?s=300&d=identicon&r=G';
});
self.showList = ko.observable(true);
self.toggleView = function () {
self.showList(!self.showList());
}
};

If I understand correctly, you could bind the visible property of each div to a boolean that you flip each time a button is pressed.
HTML:
<input type="button" value="Toggle" data-bind="click: toggleView"/>
<div data-bind="visible: showGrid()">Grid</div>
<div data-bind="visible: !showGrid()">List</div>
View Model:
var ViewModel = function() {
var self = this;
self.showGrid = ko.observable(true);
self.toggleView = function() {
self.showGrid(!self.showGrid());
}
}
var vm = new ViewModel();
ko.applyBindings(vm);
Here's a jsFiddle.

Related

knockout carrying the data to Multiple View

Below is my code which is knocokout js,i have ListviewModel which is related to two views 1st and second view as below,Both views using the class name UserDetailsView, i am binding two views 1st and second view as below,my problem is, i have click event on the 1st view "Userview" i need to get data of clicked event which is $root.UserView, when i click this it should get all related value and pass to second view so i can bind the data using knockout js ,i am getting the value but unable to bind the data when i clicked $root.UserView so i used jquery in second view for binding, but Now requirement is changed i need make another click event in second view so i can carry data to another view,before that i need to bind the second view with Knockout js how it can be done need help
function ListviewModel()
{
var self = this;
self.Listarray = ko.observableArray();
self.getUserList = function () {
var ListModel = {
userId: UserID
}
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(ListModel),
url: serverUrl + 'xxx/xxx/xxx',
success: function (data) {
self.Listarray($.map(data, function (item) {
return new Listdata(item);
}));
}
});
};
//Click Function for UserPersonalview
self.UserView = function (Listarray) {
$("#userId").text(Listarray.userIdId());
$("#userName").text(Listarray.UserName())
document.getElementById('userProfilePic').setAttribute('src', "data:" + Listarray.ProfilePictype() + ";base64," + Listarray.ProfilePicBase64());
window.location.href = "#UserPersonalview";
}
self.UserProfile = function () {
console.log(self.Listarray());
}
}
//Model
function Listdata(data)
{
var self = this;
self.userId = ko.observable(data.userId);
self.userName = ko.observable(data.userName);
self.userProfilePicBase64 = ko.observable(data.userProfilePicBase64);
self.userProfilePictype = ko.observable(data.userProfilePictype);
self.userProfilepic = ko.computed(function () {
return "data:" + self.userProfilePictype() + ";base64," + self.userProfilePicBase64();
});
}
//1st View
<div data-role="view" id="Userview" class="UserDetailsView" data-layout="default">
<div data-role="content" style="background-color:#fff!important">
<div>
<ul style="list-style: none;" data-role="listview" id="hierarchical-listview" data-bind="foreach:Listarray">
<li style="background-color:#FFF" data-bind="click:$root.UserView">
<div style="width:100%;">
<div style="width:50%;float:left">
<span data-bind="text:$data.userId" style="display:none"></span>
<img data-bind="attr: { src:$data.userProfilepic }" onclick="Imagepopover()" />
<label style="width: 25%!important;" class="firendslisttext" data-bind="text:$data.userName"></label>
</div>
<div style="width:50%;float:left;margin: 0px -20px;">
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
//second View
<div data-role="view" id="UserPersonalview" >
<header data-role="header">
<div data-role="navbar" class="UserDetailsView">
<div class="content-header ">
<ul style="list-style: none;" >
<li data-bind="click:$root.UserProfile">
<div class="km-leftitem">
</div>
<div class="block2" >
<div class="inner" style="float:left" >
<span id="userId" style="display:none"></span>
<img data-responsive="" width="40" height="40" id="userProfilePic" src="" style="border-radius: 50%;" />
</div>
<div class="inner" style="float:left;margin-left:15px">
<label id="userName" style="width: 100%!important;"></label>
</div>
</div>
<div class="km-rightitem">
<a data-align="right"><img src="images/icon-add.png" style="height:50px" /></a>
</div>
</li>
</ul>
</div>
</div>
</header>
<div data=role="content"><div>
</div>

Angular trigger js 'onclick' event

I'm trying to trigger an 'onclick' event inside of an angular controller.
<div id="galerie">
<h2>{{main.Page.title()}}</h2>
<hr>
<div class="row">
<div class="col-sm-4 col-xs-6" ng-repeat="i in page.getLans() track by $index">
<a ng-click="page.selectGalerie($index+1)" href>Playground Vol.{{$index+1}}</a>
</div>
</div>
<div id="links">
<a id="galerieLink_{{$index}}" href="img/galerie/pg{{page.galerie.volume}}/{{file}}" ng-repeat="file in page.galerie.files">{{$index}} </a>
</div>
<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls">
<div class="slides"></div>
<h3 class="title"></h3>
<a class="prev">‹</a>
<a class="next">›</a>
<a class="close">×</a>
<a class="play-pause"></a>
<ol class="indicator"></ol>
</div>
</div>
<script>
document.getElementById('links').onclick = function (event) {
event = event || window.event;
var target = event.target || event.srcElement;
var link = target.src ? target.parentNode : target;
var options = {index: link, event: event};
console.log(options);
var links = this.getElementsByTagName('a');
blueimp.Gallery(links, options);
};
</script>
I was trying it this way inside my controller:
angular.element('#galerieLink_0').trigger('click');
But it doesn't work.
Angular is not jquery. functionality belongs in the controller.
var app = angular.module("app", []);
app.controller("foo",["$scope",function($scope){
$scope.clickCount = 0;
$scope.counter = function() { $scope.clickCount++; }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="foo">
<div ng-bind="clickCount"></div>
<button ng-click="counter()" >+1</button>
</div>

Knockout.js : ObservableArray with ObservableArrays inside?

I'm using this plugin called Dragula which needs an ObservableArray as a source for the data..
HTML/Knockout-bindings
<div class="widget-container">
<div class="widget-content visible" id="team-setup">
<div class="header">
<p>Lagoppsett</p>
<p></p>
</div>
<div class="col-sm-12">
<div class="row">
<div class="widget-container">
<div class="col-xs-6 widget-content visible">
<div class="header">
<p>Tilgjengelige spillere</p>
<p></p>
</div>
<div class="player-card-container-mini" data-bind="dragula: { data: availablePlayers, group: 'playerz' } ">
<div class="player-card-mini">
<div class="player-card-left">
<div class="player-avatar" style="margin-left: 85%;">
<img src="Content/Images/player-female.png" id="imgAvatar" runat="server" />
<div class="player-shirt-no" data-bind="text: ShirtNo"></div>
</div>
</div>
<div class="player-card-subtext">
<div class="player-text">
<div class="player-card-header-small" data-bind="text: PlayerName"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 widget-content visible">
<div class="header">
<p>Lag</p>
<p></p>
</div>
<div data-bind="foreach: teamsetup">
<div data-bind="foreach: SubTeams">
<h1 data-bind="text: TeamSubName"></h1>
<div class="player-card-container-mini" data-bind="dragula: { data: Players, group: 'playerz' } " style="border: 1px solid red; min-height:200px">
<div class="player-card-mini">
<div class="player-card-left">
<div class="player-avatar" style="margin-left: 85%;">
<img src="Content/Images/player-female.png" id="img1" runat="server" />
<div class="player-shirt-no" data-bind="text: ShirtNo"></div>
</div>
</div>
<div class="player-card-subtext">
<div class="player-text">
<div class="player-card-header-small" data-bind="text: PlayerName"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="clear:both"> </div>
</div>
</div>
Knockout code :
var TeamSetupViewModel = function () {
var self = this;
self.teamsetup = ko.observableArray();
self.availablePlayers = ko.observableArray();
self.testPlayers = ko.observableArray();
}
var model = new TeamSetupViewModel();
ko.applyBindings(model, document.getElementById("team-setup"));
var uri = 'api/MainPage/GetTeamSetup/' + getQueryVariable("teamId");
$.get(uri,
function (data) {
model.teamsetup(data);
model.availablePlayers(data.AvailablePlayers);
model.testPlayers(data.AvailablePlayers);
console.log(data);
}, 'json');
});
The problem is... that i'm having a ObservableArray at the top node, and i do need ObservableArrays further down in the hierarchy.
model.availablePlayers works fine, but when accessing the other players in the html/ko foreach loops through teamsetup -> SubTeams -> Players it doesn't work due to Players isn't an ObservableArray. (There might be everyting from 1 to 7 SubTeams with players).
So how can i make the Players in each SubTeams an ObservableArray ?
See the image for the datastructure :
You could use Mapping plugin, but if players is the only thing you need, you can do it manually:
Simplify your view model:
var TeamSetupViewModel = function () {
var self = this;
self.availablePlayers = ko.observableArray();
self.subTeams = ko.observableArray();
}
After you get the data from the server, populate the view model converting the array of players on every team to an observable array of players:
$.get(uri,
function (data) {
model.availablePlayers(data.AvailablePlayers);
model.subTeams(data.SubTeams.map(function(t) { t.Players = ko.observableArray(t.Players); return t; }));
}, 'json');
});
Finally, remove the following line in your template (with its closing tag) - nothing to iterate over anymore:
<div data-bind="foreach: teamsetup">
... and update the name of the property in the next line, so it is camel case like in the VM:
<div data-bind="foreach: subTeams">

Why is extending an extended view not working in ember.js?

I am trying to create a modal view and have a base class that all modals need and then extending it for more specific functionality.
PlanSource.Modal = Ember.View.extend({
isShowing: false,
hide: function() {
this.set("isShowing", false);
},
close: function() {
this.set("isShowing", false);
},
show: function() {
this.set("isShowing", true);
}
});
PlanSource.AddJobModal = PlanSource.Modal.extend({
templateName: "modals/add_job",
createJob: function() {
var container = $("#new-job-name"),
name = container.val();
if (!name || name == "") return;
var job = PlanSource.Job.createRecord({
"name": name
});
job.save();
container.val("");
this.send("hide");
}
});
I render it with
{{view PlanSource.AddJobModal}}
And have the view template
<a class="button button-green" {{action show target=view}}>+ Add Job</a>
{{#if view.isShowing}}
<div class="modal-wrapper">
<div class="overlay"></div>
<div class="dialog box box-border">
<div class="header">
<p class="title">Enter a job name.</p>
</div>
<div class="body">
<p>Enter a name for your new job.</p>
<input type="text" id="new-job-name" placeholder="Job name">
</div>
<div class="footer">
<div class="buttons">
<a class="button button-blue" {{action createJob target=view}} >Create</a>
<a class="button" {{action close target=view}}>No</a>
</div>
</div>
</div>
</div>
{{/if}}
The problem is that when I click the button on the modal dialog, it gives me an "action createJob" can not be found. Am I extending the objects incorrectly because it works if I put the createJob in the base Modal class.
Fixed
There was an issue somewhere else in my code. The name got copied and so it was redefining it and making the method not exist.

Cannot find elements by class jQuery in just inserted HTML

render:function () {
var self = this;
$.ajax({url:'/db/list.json', dataType:'JSON'}).done(function (json) {
var html = tmpl['video-list']({videos:json});
self.$el.html(html);
});
console.log($('.video-thumb-box'));
$.each($('.video-thumb-box'), function(){
console.log(this);
$(this).bind('mouseenter', function(){
console.log($('.video-thumb-info', this));
});
});
}
tmpl['video-list']({videos:json}) is underscore template and contain list of items in DIVs here is example return
<div class="span3">
<a href="#/video/123">
<div class="video-thumb-box">
<img class="video-thumb-img" src="test" alt="Video tumbnail">
<div class="video-thumb-info hide">
<img class="pull-right" width="16" height="16" src="/img/icons/namba.png">
something
</div>
</div>
</a>
</div>
<div class="span3">
<a href="#/video/123">
<div class="video-thumb-box">
<img class="video-thumb-img" src="test" alt="Video tumbnail">
<div class="video-thumb-info hide">
<img class="pull-right" width="16" height="16" src="/img/icons/namba.png">
something
</div>
</div>
</a>
</div>
Why cannot I find anything in $('.video-thumb-box')?
your each loop is backwards.
$('.video-thumb-box').each(function() {
console.log(this);
$(this).bind('mouseenter', function(){
console.log($('.video-thumb-info', this));
});
});
Here's the jQuery .each() API page

Categories