Can Knockout.js change variable which is not in the viewModel - javascript

This is my sample code
HTML:
<input type="text" data-bind="value: a"/>
And in JavaScript I want something like.
var a = 5;
a = ko.observable(a);
But i want to keep a number. And when i change a the input to change and when I change the input a to change.

ViewModel->Scope is possible, but Scope->ViewModel is not possible:
var nonObservable = 5,
observable = ko.observable(nonObservable);
// ViewModel->Scope
observable.subscribe(function(newValue) {
nonObservable = newValue;
});
// Scope->ViewModel
observable("new value");
// This however, will not work
nonObservable = "not in any way connected";
The reason for this is that there is no way for knockout to detect what name you are binding it to (ko.observable just knows that it has been given the value 5, not that it has been given the name nonObservable) ... and even if it could detect this, you would probably not want to do this by default.

Related

2 way data binding in JavaScript

Two-way data binding refers to the ability to bind changes to an object’s properties to changes in the UI, and vice-versa.
Can we achieve 2-way data-binding with JavaScript?
Especially 2 Way Data Binding without Frameworks.
When an input is changed update the value, add a setter to the value which sets the inputs content. E.g this element:
<input id="age">
And some js:
var person = (function(el){
return {
set age(v){
el.value = v;
},
get age(){
return el.value;
}
};
})(document.getElementById("age"));
So you can do:
person.age = 15;
And the input will change. Changing the input changes person.age
Yes, we can achieve the two way data binding using pure javascript.
twoWay=function(event) {
var elem = document.getElementsByClassName(event.currentTarget.className);
for(var key in elem){
elem[key].value=event.currentTarget.value;
}
}
You can check the jsfiddle.
Simple and working approach to two-way binding, only using vanilla JS.
<!-- index.html -->
<form action="#" onsubmit="vm.onSubmit(event, this)">
<input onchange="vm.username=this.value" type="text" id="Username">
<input type="submit" id="Submit">
</form>
<script src="vm.js"></script>
// vm.js - vanialla JS
let vm = {
_username: "",
get username() {
return this._username;
},
set username(value) {
this._username = value;
},
onSubmit: function (event, element) {
console.log(this.username);
}
}
JS Getters and Setters are quite nice for this - especially when you look at the browser support.
Yes indeed.
There are frameworks like angular Js which provides full support for two way data binding.
And if you want to achieve the same in vanilla js you can bind value into view
Eg. document.getElementById('test').value="This is a Test"
And to bind view value to the controller you can trigger onchange event in html.
<Input type="text" id="test" onchange="Func()">
LemonadeJS is another micro-library (4K), with no dependencies worth looking at.
https://lemonadejs.net
https://github.com/lemonadejs/lemonadejs
Adding a little elaboration to Jonas Wilms answer, here's a sample without currying and also adds event binding for a full two way bind.
// Property binding
var person = {
set name(v) {
document.getElementById('name').value = v;
},
get name() {
return document.getElementById('name').value;
},
set age(v) {
document.getElementById('age').value = v;
},
get age() {
return document.getElementById('age').value;
}
};
// You can now set values as such
person.name = 'Cesar';
person.age = 12;
// Event binding completes the two way
function logToConsole(event) {
console.log(event.target.value);
}
// You can set person.name or person.age in console as well.
<label for="name">Name: </label><input id="name" onkeyup="logToConsole(event)">
<label for="age">Age: </label><input id="age" onkeyup="logToConsole(event)">
Would you mind if it would be a small component for databinding tasks that provides enough convenient databinding definition commands. I did it with databindjs. e.g.
// Lets assume that there is just simple form (target)
var simpleForm = {
input: $('.simple .input-value'),
output: $('.simple .output-value')
};
// And here is the simple model object (source)
var model = {
text: 'initial value'
};
// Lets set two directional binding between [input] <-> [text]
var simpleBinding = bindTo(simpleForm, () => model, {
'input.val': 'text', // bind to user input
'output.text': 'text' // simple region that will react on user input
});
// This command will sync values from source to target (from model to view)
updateLayout(simpleBinding);
subscribeToChange(simpleBinding, () => {
$('.simple .console').html(JSON.stringify(model));
});
// Just initialize console from default model state
$('.simple .console').html(JSON.stringify(model));
The full solution here.
You can check the full implementation of the databinding core on github

Call function .oninput

JSFIDDLE
HTML:
<input type="number" id="strScore" class="attribScore" min=8 max=15>
<input type="number" id="strMod" class="attribMod" readonly="readonly">
Javascript:
/****************************************************************
document.getElementById("strScore").oninput = function update(e) {
var result = document.getElementById("strMod");
var attribScore = $('#strScore').val();
result.value = (Math.floor((attribScore / 2) -5));
}
******************************************************************/
var strScore = $('#strScore').val();
var strMod = $('#strMod').val();
var update = function(score, mod) {
attribMod = (Math.floor(score / 2) - 5);
mod.value = attribMod;
};
update(strScore,strMod);
When the left input is updated with an ability score, the right input should reflect the ability modifier.
The commented section of javascript is perfectly functional, but I would really rather not have a separate function for every input that needs to be updated like this - one function is far easier to isolate and troubleshoot in the future. What I'd like to do is have one function to which I can pass the score and modifier input values as arguments (strScore and strMod in this case) and have it update the modifier field via the .oninput event. My attempt at this is below the commented section of javascript. I feel like I'm just not connecting the dots on how to call the function appropriately or correctly update the Modifier input passed to the function.
Phew. Got pulled away from the desk. Here is a solution for you. You just need to make sure that the strscore is set with an id number. This way you can relate to what strmod you want to change.
Ex. strScore1 = strMod1 and strScore2 = strMod2
This will setup a scenario where you don't have to touch anymore JavaScript to do this same function in the future. Allowing you to add as many score and mod couplets as you want in the HTML part.
We are binding the 'input' event on the class of .attributeScore which allows us to set the function. There is no need to pass in values because they are already included by default. As long as the score input has a class of .attributeScore, then it will fire that function.
We can use this.value to grab the score value, and then sub-string out the identity of the score aka 1 for strScore1 from the this.id attribute of the input field.
If we concatenate that sub-string with #strMod we can update the value of the corresponding strMod attribute with inline math.
Here is the jsfiddle: http://jsfiddle.net/hrofz8rg/
<!DOCTYPE html>
<html>
<head>
<title>Some JavaScript Example</title>
</head>
<body>
<input type="number" id="strScore1" class="attribScore" min=8 max=15>
<input type="number" id="strMod1" class="attribMod" readonly="readonly">
<br>
<br>
<input type="number" id="strScore2" class="attribScore" min=8 max=15>
<input type="number" id="strMod2" class="attribMod" readonly="readonly">
<!-- JavaScript -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(".attribScore").bind({
'input':function(){
var attrib_num = this.id.substring(8,this.length);
$('#strMod' + attrib_num).val((Math.floor(this.value / 2) - 5));
}
});
</script>
</body>
</html>
Hope that helps! Enjoy!
Modifying your function to accept to dom nodes rather than two values would allow you to reuse the function in separate events that use different dom nodes relatively easily.
/****************************************************************
document.getElementById("strScore").oninput = function update(e) {
var result = document.getElementById("strMod");
var attribScore = $('#strScore').val();
result.value = (Math.floor((attribScore / 2) -5));
}
******************************************************************/
var update = function($score, $mod) {
var attribMod = (Math.floor($score.val() / 2) - 5);
$mod.val(attribMod);
};
document.getElementById("strScore").oninput = function update(e) {
var $score = $('#strScore');
var $mod = $('#strMod');
update($score, $mod);
};
Even better though would be able to dynamically figure out which mod element you should target based on which score element the event was triggered on, then you wouldn't need a separate function to do the calculation/update while keeping the code dry.

angular controller only picks up the input values changed

I've got a fairly simple angular controller method :
$scope.addComment = function () {
if ($scope.newComment.message) {
$scope.can_add_comments = false;
new Comments({ comment: $scope.newComment }).$save(function (comment) {
$scope.comments.unshift(comment);
return $scope.can_add_comments = true;
});
return $scope.newComment = {};
}
};
And in my form I have a textarea that holds the value of comment :
<textarea class="required" cols="40" id="new_comment_message" maxlength="2500" ng-disabled="!can_add_comments" ng-model="newComment.message" required="required" rows="20"></textarea>
Works great so far, however I do want to send some data, hidden data with the comment as well. So I added something to hold that value :
<input id="hash_id" name="hash_id" ng-init="__1515604539_122642" ng-model="newComment.hash_id" type="hidden" value="__1515604539_122642">
However when I inspect the $scope.newComment it always comes back as an object with only message as it's property, which is the value from the text area, and I don't get the property on the object hash_id.
When I make this input non hidden and I manually type in the value into the input field and submit a form, I do get a object with hash_id property. What am I doing wrong here, not setting it right?
As far as I know, ng-model doesn't use the value property as a "default" (i.e. it won't copy it back into your model). If you want a default, it should be placed wherever the model is defined:
$scope.newComment = { hash_id: "__1515604539_122642", /* Other params */ };
Alternatively, changing the ng-init to an assignment should work (though I would recommend the above solution instead):
<input id="hash_id" name="hash_id" ng-init="newComment.hash_id = '__1515604539_122642'" ng-model="newComment.hash_id" type="hidden">

Get the tag name of a form input value

How does one get the .tagName of a value passed in an HTML form input? This is to check whether the value that has been passed is an 'iFrame'. The input is to only accept iframes
For example:
//HTML
<input type="text" id="iFrame">
<button id="butt">Push</button>
//JavaScript
document.getElementById("butt").onclick = function(){
var iframe = document.getElementById("iFrame").value;
console.log(iframe.tagName);
}
I think you are looking for
var iframe = document.getElementsByTagName("iFrame")
I perhaps did not ask the question in the best way, initially.
I wanted to check if the value passed in the input field was an "iframe" (the input is to only accept iFrames). Since .value returns a string and not an HTML tag, getting the tag name through basic methods would not work. I needed another way.
For anybody else who needs a quick solution, this is how I managed to do it:
document.getElementById("submit").onclick = function(){
var iframe = document.getElementById("iFrame").value;
var check1 = iframe.match(/iframe/g);
var check2 = iframe.match(/frameborder/g);
var check3 = iframe.match(/http:/g);
var check = check1.length + check2.length + check3.length;
if (check === 4) {
alert("good!");
}
}

How do I get a handle to a dynamically-generated field name in javascript?

I have a series of fields created dynamically based on database records. They will be named cardObject1, cardObject2, and so on for as many rows as necessary. I'm now trying to access a specific cardObject field in a function where the number is passed in, but am getting an error message.
The field looks like this:
<input name="cardObject241" value="2,$25.00,1" type="hidden">
The js code I'm using looks like this:
function deleteFromCart(id){
if (confirm("Are you sure you want to delete this item from your cart?")){
var voucherNbr = document.getElementById("voucherNbr").value;
var cardObjectArray = document.getElementById("cardObject"+id).value.split();
var amtToDelete = cardObjectArray[1];
alert("need to delete " + amtToDelete);
}
}
And the error I'm getting is
document.getElementById("cardObject" + id) is null
on this line:
var cardObjectArray = document.getElementById("cardObject"+id).value.split();
How can I get a handle to the cardObject field that ends with the number passed in as the id param?
You need to add an id="" attribute with the same name as the name attribute.
<input id="cardObject241" name="cardObject241" value="2,$25.00,1" type="hidden">
Firstly, your input field needs an id as well as a name, so it would look like this:
<input name="cardObject241" id="cardObject241" value="2,$25.00,1" type="hidden">
Secondly, if you have an object that may or may not exist, it's always a good idea to check for existence before you start manipulating properties:
var tempObj=document.getElementById("cardObject"+id)
if(tempObj) {
var cardObjectArray = tempObj.value.split();
...do your stuff with cardObjectArray....
}
You can use document.getElementsByName() or (cross-browser back to the Stone Age)
document.forms[formIndexOrName].elements["cardObject" + id].value.split(",")

Categories

Resources