knockout.js api search form - api

The goal of my code is to search on the API search string:
So if you fill out the form you get the hits bij name.
I used the following Knockout.js script:
var viewModel=
{
query : ko.observable("wis"),
};
function EmployeesViewModel(query)
{
var self = this;
self.employees = ko.observableArray();
self.query = ko.observable(query);
self.baseUri = BASE + "/api/v1/search?resource=employees&field=achternaam&q=";
self.apiurl = ko.computed(function() {
return self.baseUri + self.query();
}, self);
//$.getJSON(baseUri, self.employees);
//$.getJSON(self.baseUri, self.employees);
$.getJSON(self.apiurl(), self.employees);
};
$(document).ready(function () {
ko.applyBindings(new EmployeesViewModel(viewModel.query()));
});
The html binding is:
<input type="text" class="search-query" placeholder="Search" id="global-search" data-bind="value: query, valueUpdate: 'keyup'"/>
But if i fill the text box i onley get the default "wis" employees? What am I doing wrong?

Not entirely sure what is wrong here, but have you debugged it and seen what the value of query is in apiurl?
One potential issue is that you are passing employees to getJSON as the observable, not the underlying array, so you could try:
$.getJSON(self.apiurl(), self.employees());

After some digging I found a solution.
var employeesModel = function(){
var self = this;
self.u = base +'/api/v1/search';
self.resource = 'employees';
self.field = 'achternaam';
self.employees = ko.observableArray([]);
self.q = ko.observable();
//Load Json when model is setup
self.dummyCompute = ko.computed(function() {
$.getJSON(self.u,{'resource': self.resource, 'field': self.field, 'q':self.q }, function(data) {
self.employees(data);
});
}, self);
};
ko.applyBindings(new employeesModel());

Related

React Native: how can I achieve the dynamic keys with multiple objects

Here is my code I tried,
var array=[];
var list = this.state.list;
var getList = function(i){
var add = +i + 1;
return {
["value"+add]:{
Description:list[i].Description,
Length:list[i].Length,
Height:list[i].Height,
Weight:list[i].Weight,
VolumeWeight:list[i].VolumeWeight,
ActualWeight:list[i].ActualWeight,
}
}
}.bind(this)
for(var i in list){
array.push(getList(i));
}
var dataArray = array.map(function(e){
return JSON.stringify(e);
});
dataString = dataArray.join(",");
data1 = {
ConsigneeBranchName:this.state.searchText,
ConsigneeBranchCode:this.state.code,
ConsigneeBranchFullAddress:this.state.DAddress,
SenderBranchCode:this.state.code1,
SenderBranchName:this.state.searchTexts,
SenderBranchFullAddress:this.state.Address,
CreatedByEmployeeCode:id,
CreatedByEmployeeFullName:userName,
jsonString:{
JsonValues:{
id:"MyID",
values:dataString
}
}
}
But I want the result is exactly this
var result = {
"ConsigneeBranchName":"",
"ConsigneeBranchCode":"",
"ConsigneeBranchFullAddress":"",
"SenderBranchCode":"",
"SenderBranchName":"",
"SenderBranchFullAddress":"",
"CreatedByEmployeeCode":"",
"CreatedByEmployeeFullName":"",
"jsonString":"{
"JsonValues": {
"id": "MyID",
"values": {
"value1":{
"Description”:"testSmarter1",
"Length”:"60",
"Height”:"50",
"Weight”:"70",
"VolumeWeight”:"75",
"ActualWeight”:”78"
},
"value2:{
"Description":"Documents",
"Length":"120",
"Height":"68",
"Weight":"75",
"VolumeWeight":"122.4",
"ActualWeight":"123"
},
}
}
}
};
Please any one help me
I want the object with dynamic keys within a single object {key1:{des:1,value:as},key2:{des:2,value:aw},key3:{des:3,value:au}}
can you please help me I have tried so many times
see this below image I want this part, inside the single object, I can join multiple objects with dynamic keys
lodash already has a function called keyBy, you can use it to get this functionality. If adding lodash doesn't make sense in your project.
I have implemented a vanilla JS version.
function keyBy(array, mapperFn) {
const resultObj = {};
array.map(item => resultObj[mapperFn(item)] = item);
return resultObj;
}
function arrayToObject (array, keyName = 'id') {
return keyBy(array, function(element) {return element[keyName]});
}
API:
arrayToObject(targetArray, stringNameOfThePorpertyYouWantToUseAsKey);
USAGE:
const listOfUsers = [{name: 'Jenitha', reputation: 6}, {name: 'Chandan', reputation: 3}];
const mapOfUsersByName = arrayToObject(listOfUsers, 'name');

JSON Store in worklight v6.0

I am trying to integrate the JSONStore standalone app in my multipage application. When I am trying to initialize the collection I am getting the following error "Uncaught TypeError: undefined is not a function". One thing I want to know is, in Worklight version 6.0 I observed that underscore (Lo-Dash) templating was used. But nowhere I found the reference given to the lodash. Also, I didn't find the lodash file anywhere. can anyone please tell me how to do this?
Here is my javascript code
window.$ = window.jQuery = WLJQ;
currentPage = {};
currentPage.init = function(WL, jQuery, lodash) {
alert("current page ::init called");
'use strict';
//Dependencies
var $ = jQuery,
_ = lodash;
//CONSTANTS
var PEOPLE_COLLECTION_NAME = 'people',
KEY_VALUE_COLLECTION_NAME = 'keyvalue',
INIT_FIRST_MSG = 'PERSISTENT_STORE_NOT_OPEN',
NAME_FIELD_EMPTY_MSG = 'Name field is empty',
AGE_FIELD_EMPTY_MSG = 'Age field is empty',
ID_FIELD_EMPTY_MSG = 'Id field is empty',
EMPTY_TABLE_MSG = 'No documents found',
DESTROY_MSG = 'Destroy finished succesfully',
INIT_MSG = 'Collection initialized',
ADD_MSG = 'Data added to the collection',
REPLACE_MSG = 'Document replaced succesfully, call find.',
REMOVE_MSG = 'Documents removed: ',
COUNT_MSG = 'Documents in the collection: ',
CLOSE_ALL_MSG = 'JSONStore closed',
REMOVE_COLLECTION_MSG = 'Removed all data in the collection',
LOAD_MSG = 'New documents loaded from adapter: ',
PUSH_MSG_FAILED = 'Could not push some docs, res: ',
PUSH_MSG = 'Push finished',
PASS_CHANGED_MSG = 'Password changed succesfully';
$('#init').click(initCollection);
$('#destroy').click(destroy);
$('#add-data').click(addData);
$('#find-name').click(findByName);
$('#find-age').click(findByAge);
$('#find-all').click(findAll);
$('#find-id-btn').click(findById);
$('#replace').click(replace);
$('#remove-id-btn').click(removeById);
//Log messages to the console and status field
var _logMessage = function (msg, id) {
//Get reference to the status field
var status = _.isUndefined(id) ? $('div#status-field') : $(id);
//Put message in the status div
status.text(msg);
//Log message to the console
WL.Logger.info(msg);
};
//Show JSONStore document in a table
var _showTable = function (arr) {
if (_.isArray(arr) && arr.length < 1) {
return _logMessage(EMPTY_TABLE_MSG);
}
//Log to the console
WL.Logger.ctx({stringify: true, pretty: true}).info(arr);
var
//Get reference to the status field
status = $('div#status-field'),
//Table HTML template
table = [
'<table id="user_table" >',
'<tr>',
'<td><b>_id</b></td>',
'<td><b>name</b></td>',
'<td><b>age</b></td>',
'<td><b>json</b></td>',
'</tr>',
'<% _.each(people, function(person) { %>',
'<tr>',
'<td> <%= person._id %> </td>',
'<td> <%= person.json.name %> </td>',
'<td><%= person.json.age %></td>',
'<td><%= JSON.stringify(person.json) %></td>',
'</tr>',
'<% }); %>',
'</table>'
].join(''),
//Populate the HTML template with content
html = _.template(table, {people : arr});
//Put the generated HTML table into the DOM
status.html(html);
};
//Scroll to the top every time a button is clicked
$('button').on('click', function () {
$('html, body').animate({scrollTop: 0}, 'slow');
});
function initCollection() {
console.log("init collection method called");
alert("init collection method called");
//Get references to the input fields DOM elements
var usernameField = $('input#init-username'),
passwordField = $('input#init-password');
//Get values from the input fields
var username = usernameField.val() || '',
password = passwordField.val() || '';
//Create the optional options object passed to init
var options = {};
//Check if a username was passed
if (username.length > 0) {
options.username = username;
}
//If if a password was passed
if (password.length > 0) {
options.password = password;
}
//JSONStore collections metadata
var collections = {};
//Define the 'people' collection and list the search fields
collections[PEOPLE_COLLECTION_NAME] = {
searchFields : {name: 'string', age: 'integer'},
//-- Start optional adapter metadata
adapter : {
name: 'people',
add: 'addPerson',
remove: 'removePerson',
replace: 'replacePerson',
load: {
procedure: 'getPeople',
params: [],
key: 'peopleList'
}
}
//-- End optional adapter metadata
};
//Define the 'keyvalue' collection and use additional search fields
collections[KEY_VALUE_COLLECTION_NAME] = {
searchFields : {},
additionalSearchFields : { key: 'string' }
};
//Initialize the people collection
WL.JSONStore.init(collections, options)
.then(function () {
_logMessage(INIT_MSG);
_callEnhanceToAddKeyValueMethods();
})
.fail(function (errorObject) {
_logMessage(errorObject.msg);
});
}
Thanks in advance
regards
V.H.C
I observed that underscore(loadash) templating was used. But nowhere I
found the reference given to the loadash. Also, I didn't find the
loadash file anywhere. can anyone please tell me how to do this?
You can build your own version of lodash or use underscore.
The version of lodash used by worklight is in the WL_ variable. Looking at your code, maybe you want to replace _ = lodash with _ = WL_. Alternatively when you bring your own version lodash or underscore it will be assigned to the _ variable automatically.
Alternatively, you can use other string template libraries like Handlebars.js or basic string interpolation by modifying the String prototype.

Knockout validation group undefined or unable to location errors in MVC

I'm trying to work on knockout and unable to validate using knockout validation plugin.
[EDIT: update fiddle]
sample fiddle: jsfiddle.net/EHDD8
var CustVM = function () {
var self = this;
self.name = ko.observable().extend({ required: "Name is required" });
self.contact = ko.observable();
self.phone1 = ko.observable();
self.email = ko.observable().extend({email: true});
self.website = ko.observable().extend({required: "Website is required"});
self.Errors = ko.validation.group(self);
self.save = function () {
if (self.isValid()) {
alert("no error");
}
else {
alert("error");
}
alert("save clicked ");
};
self.cancel = function() {
alert("cancel clicked");
};
};
ko.applyBindings(new CustVM());
isValid is true even though i have not entered any required elements.
You are not using
ko.validation.registerExtenders();
that's why you are having problem, you can check my this ARticle:-
http://www.c-sharpcorner.com/UploadFile/cd7c2e/apply-knockout-validations-in-mvc-application/

Deferring a Dojo Deferred

I'm having a bit of a problem getting a deferred returned from a method in a widget. The method is itself returns a Deferred as it's an xhrPost. The code is as such (using dojo 1.8)
Calling Code:
quorum = registry.byId("quorumPanel");
var deferredResponse = quorum.updateSelectionCount();
deferredResponse.then(function(data){
console.log("Success: ", data);
}, function(err){
console.log("Error: ", err);
});
and the code in the widget:
updateSelectionCount: function() {
var self = this;
var deferredResponse = xhr.post({
url: "ajxclwrp.php",
content: [arguments here],
handleAs: "json"});
deferredResponse.then(function(response) {
var anotherDeferred = new Deferred();
var _boolA = true;
var _boolB = true;
dojo.forEach(response.result, function(relationshipInfo){
[do a bunch of stuff here too set _boolA and/or _boolB]
});
self._sethasRequiredAttr(_hasRequired);
self._setHasRequestedAttr(_hasRequested);
self.quorumInfo.innerHTML = quorumHtml;
// Below is not working
anotherDeferred.resolve('foo');
return anotherDeferred;
});
}
Do I need to set up another promise and use promise/all. Im confused/frustrated at this point.
TIA.
the .then() method returns another deferred. You just need to put a return statement in.
updateSelectionCount: function() {
var self = this;
var deferredResponse = xhr.post({
url: "ajxclwrp.php",
content: [arguments here],
handleAs: "json"});
return deferredResponse.then(function(response) {
var _boolA = true;
var _boolB = true;
dojo.forEach(response.result, function(relationshipInfo){
[do a bunch of stuff here too set _boolA and/or _boolB]
});
self._sethasRequiredAttr(_hasRequired);
self._setHasRequestedAttr(_hasRequested);
self.quorumInfo.innerHTML = quorumHtml;
return "foo";
});
}

Angular http testing

I have a fairly simple controller that gets a simple json list of objects ...
function ProductGroupsCtrl($scope, $http, $routeParams, sharedService, popupService) {
$scope.list = null;
$scope.selectedItem = null;
$scope.selectedItemJsonString = '';
$scope.selectItem = function (item) {
$scope.selectedItem = item;
$scope.selectedItemJsonString = JSON.stringify(item);
//alert(JSON.stringify(item));
};
$scope.closePopup = function () {
$scope.selectedItem = null;
$scope.selectedItemJsonString = '';
};
// sharedService.prepForBroadcast($routeParams.anotherVar);
$http({
method: 'GET',
url: '/ProductGroup'
}).success(function (data) {
$scope.list = data;
}).
error(function (data) {
$scope.message = 'There was an error with the data request.';
});
}
I then try to mock the request in the test class:
var scope, ctrl, $httpBackend, sharedServiceMock = {}, popupServiceMock = {};
beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$httsypBackend.expectGET('/ProductGroup').
respond([{
ProductGroupID: 5,
MenuTitle: "Promotional Products",
AlternativeText: "Coming soon - a collection of environmentally friendly Promotional Products",
OrdinalPosition: 5,
Active: false
}]);
scope = $rootScope.$new();
ctrl = $controller(ProductGroupsCtrl, {
$scope: scope,
$http: $httpBackend,
sharedService: sharedServiceMock,
popupService: popupServiceMock
});}));
However I receive an error in the testacular window object undefined. What have I done wrong here?
Found the answer. If I remove the error callback function from the $http.get method then it works, i.e. remove the following ...
error(function (data) {
$scope.message = 'There was an error with the data request.';
}
I have to say Angular sure is a steep learning curve for someone who is not a day to day JavaScript programmer (although I seem to be doing more and more). Thanks for the help anyway KatieK :-)