I use knockout here on a very basic example where I would like to pass the value of the clicked item to the function. I tried something which doesn't work. Does someone can show me how to proceed? Maybe I'm doint the wrong way?
Thanks for your help.
<div class='liveExample'>
<h2 data-bind="value: 'A', click: myFunction">Aaaaa</h2>
<h2 data-bind="value: 'B', click: myFunction">Bbbbb</h2>
<h2 data-bind="value: 'C', click: myFunction">Ccccc</h2>
</div>
// Here's my data model
var ViewModel = function() {
this.myFunction = function (elm)
{
alert('you clicked: ' + elm);
}
};
ko.applyBindings(new ViewModel()); // This makes Knockout get to work
jsFiddle here: http://jsfiddle.net/LkqTU/10229/
PS: I know we can do ...click: function () { myFunction('A'); }"> but I think there is a better way.
You can get value from event target (which is h2 element):
// Here's my data model
var ViewModel = function() {
this.myFunction = function (data, event)
{
debugger;
alert('you clicked: ' + event.target.value);
}
};
ko.applyBindings(new ViewModel());
Read more on click binding
Try:
this.myFunction = function (vm, event)
{
alert('you clicked: ' + event.srcElement);
}
this.myFunction = function (val1, val2)
{
...;
}
and in binding you must to set:
<h2 data-bind="value: 'C', click: myFunction.bind($data, 'A', 'B')">Ccccc</h2>
This must help you. You can pass any count of values by this method.
Related
I'd like to get the id of the pressed element.
I know it's a very common question but I do not want a solution in jquery (I'm trying to use it as few as possible)
I cannot modify the html, supposing is something like:
<p id='123' class='my_class'>x</p>
I cannot create something like:
<p id='123' class='my_class' onclick='console.log(this.id + " pressed");'>x</p>
This is my personal attempt:
$(document).on('click', '.my_class', this.id, function (id) {
console.log( id + " pressed!");
});
But I keep obtaining this:
[object Object] pressed!
var elems = document.getElementsByClassName("my_class");
for (var i = 0; i < elems.length; i++) {
elems[i].addEventListener('click', function() {
console.log(this.id + " pressed");
});
}
Here is solution without jquery.
You are almost right. Use the below code:
$(document).on('click', '.my_class', function () {
console.log( this.id + " pressed!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='123' class='my_class'>x</p>
Explanation
You should not be sending the third argument with this as it is not contextual. The syntax of the .on is:
.on( events [, selector ] [, data ], handler )
You can completely ignore the third option and that doesn't matter. Always, inside the function, the this will point to the current element, the event is triggered on.
And in your code, you are passing id as the parameter to the call back function, which is the event (EventObject). That's why you got [Object object].
Hope it makes sense.
id in the arguments points to the event object, make it
$(document).on('click', '.my_class', this.id, function (id) {
console.log( id.target.id + " pressed!");
});
or
$(document).on('click', '.my_class', this.id, function (e) {
console.log( e.target.id + " pressed!");
});
I have an event handler attached to checkboxes. I am using bootstrap switch http://www.bootstrap-switch.org/
I am trying to get the state value which is either true or false into a variable so I can set it to the session value.
I can get the true or false value when the state changes (as seen in the rendered code). However, I would like to get this value within events. Please check my x variable.
client.js
Template.myTemplate.rendered = function () {
$('input[name="questions"]').bootstrapSwitch('state', true, true);
$('input[name="questions"]').on('switchChange.bootstrapSwitch', function(event, state) {
console.log(state); // true | false
});
html:
<template name="myTemplate">
<div class="row">
<input type="checkbox" name="questions" unchecked> Hobby?
</div>
<div class="row">
<input type="checkbox" name="questions" unchecked> Writer?
</div>
I am trying to get the value which is printed out in console.log(state) within the rendered code into a variable within my event so I can set the session to value to either true or false.
Template.myTemplate.events({
'click input': function(event) {
var x = $(this).is(":checked").val();
Session.set("statevalue", x);
console.log(Session.get("statevalue")); // this is not printing out anything
}
});
I think I have got a lot better sollution and not directly using JQuery:
Template.myTemplate.events({
'change input': function(event) {
var x = event.target.checked;
Session.set("statevalue", x);
console.log(Session.get("statevalue"));
}
});
Take care to see that I suggest you to use change instead of click in event.
If you define id for your checkboxes, you could use
event.target.checkboxID.checked
with in Template-event.
this will return true or false if checked or not.
You should use template instance:
Template.myTemplate.events({
'click input': function(event, template) {
var x = template.$('input').is(":checked").val();
Session.set("statevalue", x);
console.log(Session.get("statevalue"));
}
});
or maybe with 'target':
Template.myTemplate.events({
'click input': function(event) {
var x = $(event.target).is(":checked").val();
Session.set("statevalue", x);
console.log(Session.get("statevalue"));
}
});
Template.myTemplate.rendered = function () {
$('input[name="questions"]').bootstrapSwitch('state', true, true);
$('input[name="questions"]').on('switchChange.bootstrapSwitch', function(event, state) {
var x = $(event.target).is(":checked");
Session.set("statevalue", x);
console.log(Session.get("statevalue"));
});
}
'click .task_checkbox'(event){
const target = event.target;
var isChecked = $("#"+event.target.id).is(":checked").val();
console.log(isChecked);
},
The event object already has all the information needed.
Template.myTemplate.events({
'click input': function(event) {
if (event.target.name === 'questions') {
Session.set("statevalue", event.target.checked);
console.log(Session.get("statevalue"));
}
}
});
I want to call the onHover function but with no suceess. The only way I managed to do this is if the function is global, but this is no what I need.
What I am trying to do is onMouseOver of some element of the dropdown to take its value and do something with it in my viewmodel.
HTML:
<div>
<div data-bind="with: myInnerViewModel">
<input type="text" data-bind="kendoDropDownList: {data: myData, value: myValue,template:'<span onMouseOver = \'onHover(this)\' title=\'${data}\'>${data}</span>'}" />
<div>
</div>
JS:
var myViewModel = function () {
this.myInnerViewModel = {
myData : [1, 2 , 3],
myValue : ko.observable(1),
onHover : function(e){
alert(1);
}
};
};
ko.applyBindings(new myViewModel());
fiddler: http://jsfiddle.net/QZWPR/30/
The issue lies with location of your function. If you were to change
onMouseOver = \'onHover(this)\'
to
onMouseOver = \'myViewModel.myInnerViewModel.onHover(this)\'
then i expect you would see your alert.
OR
you need to use the event binding on your span
<span data-bind="event: { mouseover: onHover}">
I have a Jquery event which does not trigger every time:
http://jsfiddle.net/LphjL/
My code:
thisWebsite = websiteInitialization ();
function websiteInitialization () {
companyName = "name";
var thisWebsite = new websiteConstructor(companyName);
return thisWebsite;
}
function websiteConstructor(companyName) {
this.companyName=companyName;
}
function ajaxUpdateDB(websiteElement, value) {
return $.post('/echo/html/',{html: "<p>Text echoed back to request</p>",delay: 3}
,function(a){}
,"json"
);
}
function updateDatabase(websiteElement, value) {
var promise = ajaxUpdateDB(websiteElement, value);
promise.complete(function () {
thisWebsite[websiteElement] = value;
});
}
$(document).ready(function() {
$(".websiteElement").change(function() {
updateDatabase( $(this).attr('id'), $(this).val() );
});
$("#infos").click(function() {
htmlCode = "<input class='websiteElement' id='companyName' type='text' value='"+thisWebsite.companyName+"'>";
$("#panel-content").html(htmlCode);
});
$("#homepage").click(function() {
htmlCode = "homepage";
$("#panel-content").html(htmlCode);
});
});
As you can see in the jsfiddle, the first time the input field is updated the Ajax is triggered, but:
if you click on 'Homepage', then click back on 'Generic infos' and update the input field again this time the Ajax is NOT triggered: $(".websiteElement").change event is not called the second time.
You need to bind the event using event delegation, or rebind the event after you replace the element. Below is the event delegation option:
$("#panel-content").on("change",".websiteElement",function() {
updateDatabase( $(this).attr('id'), $(this).val() );
});
If the event is bound directly on the element, the event will be lost when the element is replaced/removed.
I have code that looks like this....
function Finder(id) {
this.id = id;
this.input = $("#" + this.id + " :input[type='text']:first")[0];
$(this.input).bind('keyup'....);
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
this.input = the 1st element of type input found within 'id' which is what I will be referencing. This works fine for what I need.
What I want to do then is to bind the keyup event on 'input'. However I want the event to reference the instance method contained in my function - this.KeyUpHandler().
Also I need 'e' to be event that would have been passed into the function had I just done this on the markup for the input (onkeypress="keyuphandler();").
Any ideas how I can bind the event to the a function in the instance of the function I am working within?
function Finder(id) {
this.id = id;
this.input = $("#" + this.id + " :input[type='text']:first")[0];
that=this;
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
$(this.input).bind('keyup', this.KeyUpHandler);
}
It is important that you call bind() after defining the function!
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
$(this.input).bind('keyup', function(){
this.KeyUpHandler(event);
//more code can go here
});