knockoutjs using module pattern not working - javascript

I am trying to create simple knockout example using module pattern
var login = {}; //login namespace
//Constructor
login.UserData = function () {
var self = this;
self.UserName = ko.observable("");
self.Password = ko.observable("");
};
//View-Model
login.UserVM = function () {
this.userdata = new login.UserData(),
this.apiUrl = 'http://localhost:9090/',
this.authenticate = function () {
var data = JSON.parse(ko.toJSON(this.userdata));
var service = apiUrl + '/api/Cryptography/Encrypt';
DBconnection.fetchdata('POST', service, JSON.stringify(data.Password), response, function () { console.log('Cannot fetch data') }, null, true);
function response(res) {
console.log(res)
}
}
return {
authenticate: this.authenticate
}
}();
$(function () {
ko.applyBindings(login.UserVM); /* Apply the Knockout Bindings */
});
HTML CODE:
<form id="loginform" name="loginForm" method="POST">
<div id="form-root">
<div>
<label class="form-label">User Name:</label>
<input type="text" id="txtFirstName" name="txtFirstName" data-bind="value:login.UserData.UserName" />
</div>
<div>
<label class="form-label">Password:</label>
<input type="text" id="txtLastName" name="txtLastName" data-bind="value:login.UserData.Password" />
</div>
<div>
<input type="button" id="btnSubmit" value="Submit" data-bind="click: authenticate" />
</div>
</div>
</form>
the problem is am not able to get userdata in the viewmodel on click of submit it is returning undefined and the login object holds the changed value of textbox but on click it is returning black values.
please let me know
Also can you let me know how to implement definative module pattern in the same code.

The object you are returning from login.UserVM has only authenticate property and doesn't have userdata or apiUrl properties. So, instead using an IIFE to create an object, set login.UserVM to a constructor function similar to login.UserData. And then use new operator to create the viewModel object. Now the viewModel will have userdata and apiUrl properties (remove the return from the function)
Also, you need to change the HTML bindings to: data-bind="value:userdata.UserName". This looks for the userdata property inside the bound viewModel
var login = {}; //login namespace
//Constructor
login.UserData = function () {
var self = this;
self.UserName = ko.observable("");
self.Password = ko.observable("");
};
//View-Model
login.UserVM = function () {
this.userdata = new login.UserData(),
this.apiUrl = 'http://localhost:9090/',
this.authenticate = function () {
var data = JSON.parse(ko.toJSON(this.userdata));
console.log(data)
//var service = this.apiUrl + '/api/Cryptography/Encrypt';
//DBconnection.fetchdata('POST', service, JSON.stringify(data.Password), response, function () { console.log('Cannot fetch data') }, null, true);
function response(res) {
console.log(res)
}
}
}; // remove the () from here
ko.applyBindings(new login.UserVM()); /* Apply the Knockout Bindings */
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<form id="loginform" name="loginForm" method="POST">
<div id="form-root">
<div>
<label class="form-label">User Name:</label>
<input type="text" id="txtFirstName" name="txtFirstName" data-bind="value:userdata.UserName" />
</div>
<div>
<label class="form-label">Password:</label>
<input type="text" id="txtLastName" name="txtLastName" data-bind="value:userdata.Password" />
</div>
<div>
<input type="button" id="btnSubmit" value="Submit" data-bind="click: authenticate" />
</div>
</div>
</form>

Related

2CheckOut - TwoCheckoutException: Bad request - parameter error

So basically i am trying to implement 2checkout in my website and i have done everything from documentation but i get this error: TwoCheckoutException: Bad request - parameter error. I tried checking and playing with private/public keys and id but when i change them it says "authoization error" so i am sure they are okay. I read about addresses and everything and i have changed them but still not working.
Here is my full code:
#{
ViewData["Title"] = "Test";
}
<script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
<h2>Test</h2>
<form id="myCCForm" action="/Home/SubmitCard" method="post">
<input name="token" type="hidden" value="" />
<div>
<label>
<span>Card Number</span>
<input id="ccNo" type="text" value="" autocomplete="off" required />
</label>
</div>
<div>
<label>
<span>Expiration Date (MM/YYYY)</span>
<input id="expMonth" type="text" size="2" required />
</label>
<span> / </span>
<input id="expYear" type="text" size="4" required />
</div>
<div>
<label>
<span>CVC</span>
<input id="cvv" type="text" value="" autocomplete="off" required />
</label>
</div>
<input type="submit" value="Submit Payment" />
</form>
<script type="text/javascript">
// Called when token created successfully.
var successCallback = function (data) {
var myForm = document.getElementById('myCCForm');
// Set the token as the value for the token input
myForm.token.value = data.response.token.token;
// IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
myForm.submit();
};
// Called when token creation fails.
var errorCallback = function (data) {
if (data.errorCode === 200) {
alert("Error 200");
// This error code indicates that the ajax call failed. We recommend that you retry the token request.
} else {
alert(data.errorMsg);
}
};
var tokenRequest = function () {
// Setup token request arguments
var args = {
sellerId: "901417674",
publishableKey: "309FC596-8380-4B6F-B269-3E157A5A5D0B",
ccNo: $("#ccNo").val(),
cvv: $("#cvv").val(),
expMonth: $("#expMonth").val(),
expYear: $("#expYear").val()
};
// Make the token request
TCO.requestToken(successCallback, errorCallback, args);
};
$(function () {
// Pull in the public encryption key for our environment
TCO.loadPubKey('sandbox');
$("#myCCForm").submit(function (e) {
// Call our token request function
tokenRequest();
// Prevent form from submitting
return false;
});
});
</script>
and here is server side code:
public IActionResult SubmitCard()
{
TwoCheckout.TwoCheckoutConfig.SellerID = "901417674";
TwoCheckout.TwoCheckoutConfig.PrivateKey = "4E704021-B233-435F-A904-47B2620B9E66";
TwoCheckout.TwoCheckoutConfig.Sandbox = true;
try
{
TwoCheckout.AuthBillingAddress Billing = new TwoCheckout.AuthBillingAddress();
Billing.addrLine1 = "123 Main Street";
Billing.city = "Townsville";
Billing.zipCode = "43206";
Billing.state = "Ohio ";
Billing.country = "USA";
Billing.name = "Joe Flagster";
Billing.email = "Ex#a.com";
Billing.phoneNumber = "065";
TwoCheckout.ChargeAuthorizeServiceOptions Customer = new TwoCheckout.ChargeAuthorizeServiceOptions();
Customer.total = 1;
Customer.currency = "USD";
Customer.merchantOrderId = "12";
Customer.billingAddr = Billing;
Customer.token = Request.Form["token"];
TwoCheckout.ChargeService Charge = new TwoCheckout.ChargeService();
var result = Charge.Authorize(Customer);
return View("Success", result);
}
catch(TwoCheckout.TwoCheckoutException ex)
{
return View("Error", ex.ToString());
}
}
and here is all info from my sandbox:
You may need to update your site settings for sandbox from Site Management -> Site Settings and Turn to On for Demo Settings and check again
May it helps you

trouble to push objects in array and it alway be empty

I want to select object from ng-repeat list and insert it in a array, then display each attribute of the selected object in a form. My problem is that I can not insert the object in array, but able to select it. I have narrowed down error. The checkList array is always empty no matter how frontend interface interacts with it(click on checkbox). I have no idea what cause this issue?
My code:
In product.view.html:
<h1>Welcome!</h1>
<p>You're in Product profolio!!</p>
<h3>All Products:</h3>
<ul>
<li ng-repeat="product in vm.allProducts track by $index">
{{product.id}} -- {{product.product_name}} -- {{product.product_image}} -- {{product.category}} -- {{product.published_time}} -- {{product.store_id}}
<input type="checkbox" ng-model="bool" ng-change = "vm.sync(bool,product)"> {{bool}}
</li>
</ul>
{{vm.checkList}}
<form novalidate class="simple-form">
Product Name: <input type="text" ng-model="vm.checkList[0].product_name" /><br />
product_image: <input type="text" ng-model="vm.checkList[0].product_image" /><br />
Category: <input type="text" ng-model="vm.checkList[0].category" /><br />
publish time: <input type="text" ng-model="vm.checkList[0].published_time" /><br />
store ID: <input type="number" ng-model="vm.checkList[0].store_id" /><br />
</form>
- <button ng-click="vm.createProduct(vm.checkList)">Create</button>
- <button ng-click="vm.updateProduct(vm.checkList)">Update</button>
- <button ng-click="vm.deleteProduct(vm.checkList.id)">Delete</button>
<p> </p>
<p>Logout</p>
In productController.js:
(function () {
'use strict';
angular
.module('app')
.controller('ProductController', ProductController);
ProductController.$inject = ['UserService', '$rootScope'];
function ProductController(UserService, $rootScope) {
var vm = this;
vm.allProducts = [];
vm.checkList = [];
vm.deleteProduct = deleteProduct;
vm.createProduct = createProduct;
vm.updateProduct = updateProduct;
vm.isChecked = isChecked;
vm.sync = sync;
initController();
function initController() {
loadAllProduct();
}
function loadCurrentProduct(productname) {
UserService.GetByUsername(username)
.then(function (product) {
vm.product = product;
});
}
function loadAllProduct() {
var url = 'http://127.0.0.1:8000/products';
UserService.GetAll(url)
.then(function (products) {
vm.allProducts = products;
});
}
function deleteProduct(id) {
var url = 'http://127.0.0.1:8000/products/';
UserService.Delete(url,id)
.then(function () {
console.log('flash page!')
loadAllProduct();
console.log('done!')
});
}
function createProduct(product){
var url = 'http://127.0.0.1:8000/products';
UserService.Create(url,product)
.then(function(){
console.log('has creaet product!')
loadAllProduct();
console.log('done!')
});
}
function updateProduct(product){
var url = 'http://127.0.0.1:8000/products/';
UserService.Update(url,product)
.then(function(){
console.log('has upadte product!')
loadAllProduct();
console.log('done!')
});
}
function sync(bool,product){
console.log("get into sync!");
console.log(bool);
if(bool)
{
vm.checkList.push[product];
console.log(vm.checkList);
console.log(product);
}
else
{
for(var i=0; i < vm.checkList.length; i++)
{
if(vm.checkList[i].id == product.id)
{
vm.checkList.splice(i,1);
}
}
}
}
}
})();
My page:
My error shows in console:

JS wont recognize a variable within angular controller object

Im trying to create a simple login verification, however the validation function seizes to function when the validation comparison begins, and the console sais that the variable "userName is not defined" although it clearly is.
Can enyone tell me what am i defining wrong?
the angular controller code:
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
this.userName = "";
this.password = "";
this.userNameValid = true;
this.passwordValid = true;
/*submit the form*/
this.submit = function () {
alert("submit");
this.validate();
};
/* make sure user name and password has been inserted*/
this.validate = function () {
alert("validate");
var result = true;
this.userNameValid = true;
this.passwordValid = true;
if (this.userName == "") {
alert("username="+userName);
this.userNameValid = false;
result = false;
}
if (this.password == "") {
this.passwordValid = false;
result = false;
}
alert("validuserNameValid==" + userNameValid + " passwordValid==" + passwordValid);
return result;
};
});
the HTML form:
<body ng-app="LoginApp" ng-controller="LoginController as LoginController">
<form role="form" novalidate name="loginForm" ng-submit="LoginController.submit()">
<div id="loginDetails">
<div class="form-group">
<label for="user"> User Name:</label>
<input type="text" id="user" class="form-control" ng-model="LoginController.userName" required />
<span ng-show="LoginController.userNameValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" id="password" class="form-control" ng-model="LoginController.password" required />
<span ng-show="LoginController.passwordValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
{{"entered information:" +"\n"+LoginController.userName+" "+ LoginController.password}}
</div>
</div>
</form>
</body>
the log:
Error: userName is not defined
this.validate#http://localhost:39191/login.js:23:13
this.submit#http://localhost:39191/login.js:11:9
anonymous/fn#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js line 231 > Function:2:292
b#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:126:19
Kc[b]</<.compile/</</e#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:195
uf/this.$get</m.prototype.$eval#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:103
uf/this.$get</m.prototype.$apply#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:335
Kc[b]</<.compile/</<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:245
Rf#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:37:31
Qf/d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:36:486
Always use this judiciously. I would recommend you to store the reference of this in variable then use it wherever required.
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
//Store the reference of this in a variable
var lc = this;
//Use the stored refrence
lc.userName = "";
/* make sure user name and password has been inserted*/
lc.validate = function () {
if (lc.userName == "") {
alert("username="+userName);
lc.userNameValid = false;
result = false;
}
};
});
inside your alert boxes you have not mentioned this.userName try removing the alert boxes or change them.

Knockout.js enable save only if value change

I have a simple html page with value input and save button.
I want the save will be enabled only if the value is changed (somtimes is initialized and somtimes not.
I've tryied few things without any success
HTML
<input type="text"
placeholder="type here"
data-bind="value: rate,"/>
<button data-bind="click: save">Save</button>
JS
var viewmodel = function () {
this.rate = ko.observable('88').extend(required: true);
};
viewmodel.prototype.save = function () {
alert('save should be possible only if rate is changed);
};
Also on jsfiddle
Should be able to achieve this with a computed observable and the enable binding.
See http://jsfiddle.net/brendonparker/xhLrB/1/
Javascript:
var ctor = function () {
var self = this;
self.originalRate = '88';
self.rate = ko.observable('');
self.canSave = ko.computed(function(){
return self.originalRate == self.rate();
});
};
ctor.prototype.save = function () {
alert('save should be possible only if rate is changed');
};
ko.applyBindings(new ctor());
HTML:
<input type="text" placeholder="type here" data-bind="value: rate, valueUpdate: 'afterkeydown'"/>
<button data-bind="click: save, enable: canSave">Save</button>

Javascript constructor property not working when called

I'm having trouble creating a constructor property. In the firebug console the error says "telekomApp.validation.run is not a function". The this.run() function should be a property of TelekomApp constructor and I expect it too work as telekomApp.validation.run(), but it's not.
Please can you shed some light on this?
Many Thanks
JS:
(function(global) {
var TelekomApp = function() {
this.validation = function() {
var userNameField = document.getElementById("username-field"),
passwordField = document.getElementById("password-field"),
usernameMsg = document.getElementById("username-msg"),
passwordMsg = document.getElementById("password-msg");
this.run = function(tag) { // this method doesn't work...
var o = this;
};
};
};
// make global
global.TelekomApp = TelekomApp;
// instanciate
var telekomApp = new TelekomApp;
// initialise validation...
telekomApp.validation.run(document.getElementById("login-form"));
}(window));
HTML:
<div id="login">
<p id="message"></p>
<form id="login-form" action="#" method="post">
<fieldset>
<legend>Please login using your username and password</legend>
<ol>
<li>
<label for="username-field">Username <span>*</span></label>
<input type="text" id="username-field" placeholder="Type your username" />
<span id="username-msg"></span>
</li>
<li>
<label for="password-field">Password <span>*</span></label>
<input type="password" id="password-field" placeholder="Type your password" />
<span id="password-msg"></span>
</li>
<li id="button">
<input type="submit" id="login-btn" value="Log In" />
</li>
</ol>
</fieldset>
</form>
</div>
(function(global) {
var Validation = function() { //constructor for Validation
var userNameField = document.getElementById("username-field"),
passwordField = document.getElementById("password-field"),
usernameMsg = document.getElementById("username-msg"),
passwordMsg = document.getElementById("password-msg");
this.run = function(tag) { // this method doesn't work...
var o = this;
};
};
var TelekomApp = function() {
this.validation = new Validation();
};
// make global
global.TelekomApp = TelekomApp;
// instanciate
var telekomApp = new TelekomApp;
// initialise validation...
telekomApp.validation.run(document.getElementById("login-form"));
}(window));
telekomApp.validation.run would be added to the object when telekomApp.validation is called.
this.validation = function() { adds the function to the object but does not call it. Moreover this.run = function(tag) { adds run directly to telekomApp, not to telekomApp.validation.
A small change would do:
var Validation = function() {
...// your code here
}
this.validation = new Validation();

Categories