Knockout foreach binding not working for me [duplicate] - javascript

This question already has an answer here:
Knockout observableArray not updating
(1 answer)
Closed 9 years ago.
My observablearrary "assignedbranches" contains objects when I run this page. But a that has foreach binding to the array is completely empty. Why?
var branchAssignment = function (data) {
this.branchNumber = data.BranchNumber;
this.branchName = data.BranchName;
this.branchlabel = data.BranchLabel;
}
var AppViewModel = function() {
var me = this;
me.assignedbranches = ko.observableArray([]);
me.LoadBranchAssignments = function () {
$.getJSON("api/branchassignments", function (data) {
var sorted = _.sortBy(data, function (b) {
return b.BranchName;
});
$.each(sorted, function (key, val) {
me.assignedbranches().push(new branchAssignment(val));
});
});
};
me.selectBranch = function (data, e) {
console.log(data);
};
me.selectedBranch = ko.observable("Baton Rouge (4001)");
};
var appv = new AppViewModel;
ko.applyBindings(appv);
HTML
<ul class="nav navbar-nav">
<li class="dropdown">
<span data-bind="text: selectedBranch()"></span> <b class="caret"></b>
<ul class="dropdown-menu" data-bind="foreach: assignedbranches ">
<li>
</li>
</ul>
</li>
</ul>
SAMPLE branchAssignment objects
[{"branchNumber":"4042","branchName":"Albuquerque","branchlabel":"Albuquerque (4042)"},{"branchNumber":"4006","branchName":"Alexandria","branchlabel":"Alexandria (4006)"},{"branchNumber":"1118","branchName":"Arden","branchlabel":"Arden (1118)"},{"branchNumber":"1113","branchName":"Ashland","branchlabel":"Ashland (1113)"},{"branchNumber":"4019","branchName":"Atlanta","branchlabel":"Atlanta (4019)"},{"branchNumber":"4030","branchName":"Austin","branchlabel":"Austin (4030)"},{"branchNumber":"1054","branchName":"Bakersfield","branchlabel":"Bakersfield (1054)"},{"branchNumber":"1115","branchName":"Baltimore","branchlabel":"Baltimore (1115)"},{"branchNumber":"4001","branchName":"Baton Rouge","branchlabel":"Baton Rouge (4001)"}]

Try:
me.assignedbranches.push(new branchAssignment(val));
instead of:
me.assignedbranches().push(new branchAssignment(val));

Related

Execute function with onShow with Materialize doesnt work

I'm trying to call a function when the tab is changed. Nothing is happening though, does someone see my mistake?
V1:
var elem = $('.tabs')
var options = { onShow: tabChange}
var init_tabs = M.Tabs.init(elem, options);
var instance_tabs = M.Tabs.getInstance(elem);
function tabChange() {
console.log("tab has changed");
}
V2:
document.addEventListener("DOMContentLoaded", function () {
var elem = document.getElementById("periodselector");
var options = { onShow: tabChange }
var init_tabs = M.Tabs.init(elem, options);
});
function tabChange() {
console.log("tab has changed");
}
here the HTML:
<div class="card-tabs">
<ul class="tabs tabs-fullwidth " id="periodselector">
<li class="tab col s3 "><a id="daySelector" class=" " href="#DayTab">Tag</a> </li>
<li class="tab col s3 "><a id="monthSelector" class=" " href="#MonthTab">Monat</a> </li>
<li class="tab col s3 "><a class=" " href="#YearTab">Jahr</a> </li>
</ul>
</div>
On the elem var you should put the javascript object instead of the jQuery one.
From materialize doc:
var instance = M.Tabs.init(el, options);
// Or with jQuery
$(document).ready(function(){
$('.tabs').tabs();
});
Try var elem = $('.tabs')[0] or var elem = $('.tabs').eq(0)
I have not tested this but I believe it will fix your problem

Arranging multiple outputs from forEach function into one array in javascript

I'm trying to get the hrefs from the li elements with javascript. My function looks like this:
function checkUrl() {
checkUrl = function(){};
function hrefHome() {
var listCont = document.querySelectorAll(".wpcm-listings-item");
listCont.forEach(Children);
function Children(item) {
var Child = item.children;
var Hrefs = Child[0].href;
console.log(Hrefs);
}
}
}
This is returning my hrefs like I want it to, but now I need to put all of them in localStorage. I tried adding localStorage.vehHrefs = Hrefs; after the variable Hrefs, but the second one overwrites the first. What I want to do is create an array of all the hrefs and then put the array in localStorage but I need some help. Below is my HTML.
<div class="wpcm-vehicle-results-wrapper">
<ul class="wpcm-vehicle-results">
<li class="wpcm-listings-item wpcm-listings-item-featured">
<a href="http://localhost/sr19repairables/vehicle/asdfasdf/">
<div class="wpcm-listings-item-image-wrapper">
<img src="Chevy.jpg" class="wp-post-image" onload="checkUrl()"
</div>
</a>
</li>
<li class="wpcm-listings-item wpcm-listings-item-featured">
<a href="http://localhost/sr19repairables/vehicles/repairables/2020-gmc-sierra/">
<div class="wpcm-listings-item-image-wrapper">
<img src="Chevy1.jpg" class="wp-post-image" onload="checkUrl()">
</div>
</a>
</li>
</ul>
</div>
In this case, you should use map rather than forEach:
function checkUrl() {
checkUrl = function () {};
function hrefHome() {
var listCont = document.querySelectorAll('.wpcm-listings-item');
var hrefs = [...listCont].map(function Children(item) {
var Child = item.children;
return Child[0].href;
});
console.log(hrefs);
// To add it to localstorage:
localStorage.setItem('key',JSON.stringify(hrefs));
}
}
Try:
function checkUrl() {
checkUrl = function(){};
function hrefHome() {
var listCont = document.querySelectorAll(".wpcm-listings-item");
var HrefArr = [];
listCont.forEach(Children);
localStorage.vehHrefs = JSON.stringify(HrefArr);
function Children(item) {
var Child = item.children;
var Hrefs = Child[0].href;
HrefArr.push(Href)
console.log(Hrefs);
}
}
}

How can I find a <ul> elements from dropdown in a page using Protractor?

<ul _ngcontent-c9 class="results-dropdown">
<li _ngcontent-c9>
<a _ngcontent-c9>XYZ</a>
</li>
</ul>
I want to find XYZ value from dropdown and click on it.
Please let me know if anyone is having guideline for the same.
TIA
var dropdown = element(by.css('ul'));
var dropdownValues = element(by.css('ul > li > a'));
var expectedText = 'XYZ';
dropdown.click();
return dropdownValues.filter((eachValue) => {
return eachValue.getText().then((valueText) => {
if (valueText === expectedText) {
return eachValue.click();
}
});
});
or
var dropdown = element(by.css('ul'));
var expectedText = 'XYZ';
dropdown.click();
element(by.linkText(expectedText)).click();

How to render data with Handlebars and jQuery

I have this html where I need to render the data
default.hbs
<div class="chart-container" data-action="chartContainer">
<ul>
<li class="department">
<h3>Enterprise</h3>
<ul class="sections">
// HERE I NEED TO RENDER THE DATA IN AN <li> TAG
</ul>
</li>
</ul>
</div>
and here is the code
APP.chartContainer = (function () {
var Handlebars = window.Handlebars;
var bindEventsToUI = function () {
$.getJSON('maindata.json')
.done(function(data) {
localStorage.setItem('jsonData', JSON.stringify(data));
}).fail(function(err) {
console.log(err);
});
var chartContainerTemplate = $(".chart-container").html();
var theTemplate = Handlebars.compile(chartContainerTemplate);
var getData = localStorage.getItem('jsonData');
var iterateObj = $.each(JSON.parse(getData), function(key, val) {
return val;
});
var theCompiledHtml = theTemplate(iterateObj[0].enterprise);
$(".sections").append(theCompiledHtml);
};
var init = function (element) {
bindEventsToUI();
};
/**
* interfaces to public functions
*/
return {
init: init
};
}());
the function iterateObj returns this
[
{
"enterprise":[
{
"id":"10",
"name":"Hellen Quesada",
"role":"Principal Software Engineer"
},
{
"id":"11",
"name":"Jonathan Chavez",
"role":"Principal Creative Engineer"
}
]
},
{
"consumer":[
{
"id":"18",
"name":"Helga Martinez",
"role":"Production Manager"
},
{
"id":"19",
"name":"Leroy Bernard",
"role":"Sr. Software Engineer"
}
]
}
]
but all I need to render for now is the enterprise part of the data, that is why in my function I am doing iterateObj.[0].enterprise but I am not getting anything in the DOM yet, how do I iterate properly in the over the object in order to get the rendering of the data I need?
What am I missing ?
The template needs to be a script not html. The script can contain the needed html though.
<script id="foo" type="text/x-handlebars-template">
<div class="chart-container" data-action="chartContainer">
<ul>
<li class="department">
<h3>Enterprise</h3>
<ul class="sections">
//Not really sure what you want here
//But access the data like this
<li>{{enterprise.id}}</li>
</ul>
</li>
</ul>
</div>
</script>
Then you compile the template (ie the script):
//var chartContainerTemplate = $(".chart-container").html();
//rename the script to a better id
var chartContainerTemplate = $("#foo").html();
Lastly I would highly suggest reading the docs. There are ways of looping and accessing data. The above template is very basic.

Durandal 2.0 - Update the value of an observable in the view

I'm new to Durandal, my question has probably a very simple issue.
I load a list into a dropdown and the current value on the link which display the dropdown,
And the value of the link which display the dropdown is not updated correctly when an other value is selected.
But actually, I can't set the value of the observable in the select function.
View Model
var self = this;
self.system = require('durandal/system');
IPsKeys: ko.observableArray([]),
ipKeys: ko.observable(""),
activate: function (context) {
var that = this;
that.IPsKeys([]);
that.ipKeys("");
return $.when(
service.getIPSbyClientId(context.clientId).then(function (json) {
$.each(json, function (Index, Value) {
var ClientLobUWYear = {
NameLob: Value.LineOfBusiness.Name,
NameUWYear: Value.UnderwritingYear
};
that.IPsKeys().push(ClientLobUWYear);
// HERE MY VALUE IS GOOD UPDATING AND THE BINDING WORK
if (Index=== 0) {
that.ipKeys(ClientLobUWYear);
}
});
})
).then(function () {
//do some other datacontext calls for stuff used directly and only in view1
});
},
select: function (item) {
this.ipKeys = {
IdClient: item.IdClient,
IdLob: item.IdLob,
NameLob: item.NameLob,
NameUWYear: item.NameUWYear
};
/** PROBLEMS HERE **/
/** Uncaught TypeError: undefined is not a function **/
this.ipKeys(ClientLobUWYear);
},
View
<a id="select_lob-UWYear" class="dropdown-toggle" data-toggle="dropdown" href="#">
<span class="controls_value" data-bind="text: ipKeys().NameLob">ALOB</span>
<span class="controls_value" data-bind="text: ipKeys().NameUWYear">AYEAR</span>
</a>
<ul id="dropdown_year" class="dropdown-menu" data-bind="foreach: IPsKeys().sort(sortByLobYear)">
<li>
<a href="#" data-bind="click: $parent.select">
<span class="controls_value" data-bind="text: NameLob">Cargo</span>
<span class="controls_value" data-bind="text: NameUWYear">2014</span>
</a>
</li>
</ul>
Thanks a lot
The way you update an observable is like this:
var someObservable = ko.observable(""); //setting to "";
someObservable("Something else"); //updating to "Something else"
Not like this (which you are doing above)
var someObservable = ko.observable(""); //setting to "";
someObservable = "Something else";
This is overwriting someObservable with a string of value "Something else" and so is no longer an observable which is why it will not update the ui.
[JS Fiddle showing how to set observables.]

Categories