KnockoutJS click binding never called - javascript

function UserModel() {
self.forgeTransactions = function() {
console.log("forgeTransaction()");
}
self.navigateToNew() = function {
console.log("navigateToNew()");
}
}
ko.applyBindings(new UserModel());
<button class="btn" style="float: right" data-bind:"click: forgeTransactions">Add fake transaction</button>
The problem with this code is that forgeTransaction is never called whilst if i change the click binding to navigateToNew i can clearly see "navigateTwo" on the console.
Why is this happening?
Note: I can attach the entire source if needed.

You should write data-bind= not data-bind:

Your function is called forgeTransactions but you are attempting to call forgeTransaction in the button data-bind.

Related

Materialize Datepicker Only Update if Done button clicked

I am using the materializecss Datepicker (https://materializecss.com/pickers.html), and this seems like it should be really straightforward so I'm losing my mind a bit over it. Put simply, I'm trying to trigger an event only if the "Ok" button is clicked, but cannot identify that in the onClose() function provided. If I try to listen for the specific button click, I lose all that comes with the onClose() function (which nicely packages up all the info I need on that event).
Is there any way, with the onClose() function, that I can identify which button caused that onClose() to fire?
I'm admittedly a novice when it comes to javascript and jquery, so any help is appreciated.
HTML
<input type="text" class="datepicker" value="8/4/2018" job="533">
Javascript Code to initialize the datepicker
$(document).ready(function(){
$('.datepicker').datepicker({
"format": "m/d/yyyy",
onClose() {
// only do something if this was fired from the "Done" button
}
})
});
Datepicker modal created
<div class="modal datepicker-modal" id="modal-a5a43c91-2426-5565-c216-1d8ccd0cfc1d" tabindex="0">
<div class="modal-content datepicker-container">
<div class="datepicker-date-display">
<span class="year-text">
</span>
<span class="date-text">
</span>
</div>
<div class="datepicker-calendar-container">
<div class="datepicker-calendar">
</div>
<div class="datepicker-footer">
<button class="btn-flat datepicker-clear waves-effect" style="visibility: hidden;" type="button">
</button>
<div class="confirmation-btns">
<button class="btn-flat datepicker-cancel waves-effect" type="button">
Cancel
</button>
<button class="btn-flat datepicker-done waves-effect" type="button">
Ok
</button>
</div>
</div>
</div>
</div>
</div>
This code below can help you get the right button you want to do some stuff with it. Add 2 listeners to the done and cancel buttons of that opened modal right in onOpen(), and remove listeners onClose().
This will work for you.
<script>
$(document).ready(function() {
function Cancel() {
if(!this.hasEvent) {
this.hasEvent = true;
console.log('Clicked on cancel btn:', this.cancelBtn);
}
}
function Done() {
if(!this.hasEvent) {
this.hasEvent = true;
console.log('Clicked on done btn:', this.doneBtn);
}
}
$('.datepicker').datepicker({
"format": "m/d/yyyy",
onOpen: function(e) {
var that = this;
that.hasEvent = false;
this.cancelBtn.addEventListener('click', Cancel.bind(that))
this.doneBtn.addEventListener('click', Done.bind(that))
},
onClose: function(e) {
var that = this;
this.cancelBtn.removeEventListener('click', Cancel.bind(that))
this.doneBtn.removeEventListener('click', Done.bind(that))
}
})
});
</script>
First you can initialize the Datepicker just by using vanillaJS, then if you check materialize.css file then you'll find the class name of Ok button, that is, .datepicker-done. You can attach addEventListener to this button and call any function you want.
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelector('.datepicker');
var instance = M.Datepicker.init(elems);
var doneBtn = document.querySelector('.datepicker-done');
doneBtn.addEventListener('click', callThis); //Attaching a 'click' event to done button
function callThis() {
console.log('Done Button clicked only!'); //Checking the done button click
console.log(elems.getAttribute('job')); //To get the job attribute value
}
});
All of the responses were extremely helpful in figuring this out, thank you to those who contributed!
I don't know if this is the most elegant solution, but it is working for me. I kept the jquery call to initialize all of the datepickers on the page, then added the event listeners with a forEach loop. To get the values I wanted, I had to do that crazy looking series of .parent() calls, but it consistently gets me the right information. Hopefully this helps someone dealing with the same issue in the future (or it can help someone else provide a more effective answer!).
$(document).ready(function(){
$('.datepicker').datepicker({
"format": "m/d/yyyy",
})
});
document.addEventListener('DOMContentLoaded', function () {
var doneBtn = document.querySelectorAll('.datepicker-done');
doneBtn.forEach(function(elem) {
elem.addEventListener('click', callThis)
});
});
function callThis() {
var update = $(this).parent().parent().parent().parent().parent().siblings('input');
// do the thing I want with that input value
};

I am getting Reference error:checkout not defined

I have a button named checkout.But onclick i'm getting this error : Reference error:checkout not defined
My button code is :
<input type="button" value="Checkout" title="Checkout" class="button checkout" onclick="checkout()">
When i click on the button i want to show user-info
javascript code is:
$(function(){
$('.add-cart').html('+');
function checkout(){
$('.cart-status').hide(slow);
$('.user-info').show(slow);
}
});
Checkout is defined inside another function so it is not accessible from the global scope. You can put it in the global scope:
$(function () {
$('.add-cart').html('+');
});
function checkout() {
$('.cart-status').hide('slow');
$('.user-info').show('slow');
}
But a better solution is to stop putting event handlers in your HTML markup:
<input type="button" value="Checkout" title="Checkout" class="button checkout" />
$(function(){
function checkout() {
$('.cart-status').hide('slow');
$('.user-info').show('slow');
}
$('.add-cart').html('+');
$('.button.checkout').click(checkout);
});
(Note: Another problem in your code was that you were using the undefined variable slow instead of the string value 'slow', but scoping was preventing checkout() from being called at all.)

Knockout VIewModel triggers function inside foreach

I am fighting with strange issue and i am running out of ideas.
The problem is that my view model is triggering function inside foreach on click. So in this case if i click on div menuConnections testcall function is being triggered. Even if i send other value to testcall (such as div id) same value is being sent when I click on menuConnections.
How to stop this and force testcall to be executed only when i click on TheDivWhoCalls?
function ProfileViewModel(userId) {
var self = this;
self.connectionRequests = ko.observableArray();
self.getConnections = function () {
$("#menuConnections").css({ "display": "block" });
//other code which returns data
};
self.testcall = function(data) {
alert(target);
};;
}
<div id="menuConnections" data-bind='click: getConnections'>Connections</div>
<div id="connections" style="display: none">
<div data-bind="foreach: connectionRequests">
<div id="TheDivWhoCalls" data-bind='click: $root.testcall("asd")'><img src="~/Resources/Images/yesIcon.png" /></div>
</div>
</div>
I can't tell for sure without seeing an actual running example with ko.applyBindings but try changing
data-bind='click: $root.testcall("asd")
to
data-bind='click: $parent.testcall.bind($parent, "asd")
Explanation:
First I changed $root to $parent. I don't know what your $root is, but its safe to assume that your $parent is the VM with the testcall method.
More importantly, is that click: expects a function, but $root.testcall("asd") invokes the function returning undefined. Instead we use Function.prototype.bind to create a new function from testcall with the parameter set to "asd"and this set to $parent
You might need the bind syntax instead. Try data-bind="$root.testcall.bind($data, 'asd')"

Change the value of button

In my html page I'm having one div element as subbutton. In javascript I'm appending button to this div element.
$.each(responseObj.me, function (i, me) {
$('#subbutton').append('<input type="button" value=subscribe id="subscribe" background-color="green" onclick="">'+'</input>');
var subscribe=check();
function check()
{
if(responseObj.me[i].isSubscribed==="false")
{
document.getElementById("subscribe").value="I Trust";
$('#subbutton').click(function() {
sub(text);
document.getElementById("subscribe").value="Trusted";
});
}
else
{
document.getElementById("subscribe").value="Trusted";
$('#subbutton').click(function() {
unsub(text);
document.getElementById("subscribe").value="I Trust";
});
}
}
But the problem is when I click on the button first time, it's able to subscribe if it's not subscribed and able to unsubscribe if it's already subscribed. But if again I want to subscribe who is unsubscribed then it's not unsubscribed.sub(text) is a function used to subscribe person and unsub(text) is a function to unsubscribe person.
you can use,
$(document).on("click",".subscribe",function(){
//your code here
});
i created a jsfiddle. just check it out whether that is your aim
http://jsfiddle.net/2dAf9/
is you are calling check method more than one time??
then instead of using $('#subbutton').click() you have to use $('#subbutton').unbind("click").bind("click",function(){});
because it will not clear the click event it first initialized. it will call both funcitons.
try this way

Angular js ng-click is not working as expected

While working on basic angular examples ng-click is not working as expected
the following is my html code :
<form ng-submit="requestFunding()" ng-controller="StartUpCalculator">
Starting :
<input ng-change='ComputeNeeded()' ng-model='funding.StartingEstimate'>Recommedation : {{needed}}
<button>Fund me</button>
<button ng-click="reset()">Reset</button>
</form>
Javascript code :
function StartUpCalculator($scope)
{
$scope.funding = {
StartingEstimate: 0
};
ComputeNeeded = function ()
{
$scope.needed = $scope.funding.StartingEstimate * 10;
};
$scope.requestFunding = function ()
{
window.alert("Whoa!");
};
}
whenever i click Reset(reset()) button it executes requestFunding function
Thre is no $scope.reset() in controller. You are triggering the ng-submit by clciking the button.
You can change <button> to <button type="button"> so it won't be bound to form submit. By default any button in a form with no type, and no click handler to preventDefault(), will trigger submit, however type="button" will not.
You also need to change ComputeNeeded to $scope.ComputeNeeded if you want it to work with ng-change
Because on ng-submit you are calling requestFunding. Add a new button and call requestFunding from there or else remove reset from form tag and place it putside.

Categories