I am working on KnockoutJs and I have used valueUpdate:'afterkeydown' with textboxes and valueUpdate: 'change' with select elements to subscribe the respective changes and do SAME task. I want to call a same function via subscribe after each of their value changes.
To make it more clear, I'm onto something like below:
<input type="text" data-bind="value: val1, valueUpdate: 'afterkeydown'"/>
<input type="text" data-bind="value: val2, valueUpdate: 'afterkeydown'"/>
<select data-bind="value: sel1, valueUpdate:'change'">
<select data-bind="value: sel2, valueUpdate:'change'">
And in javascript, I've subscribed every changes like this:
viewModel.val1.subscribe(function () {
doSameWork();
});
viewModel.val2.subscribe(function () {
doSameWork();
});
viewModel.sel1.subscribe(function () {
doSameWork();
});
viewModel.sel2.subscribe(function () {
doSameWork();
});
################################
var doSameWork = function(){ alert('some work done!'); };
If I'm calling same function with every valueUpdate, then I was wondering if there is any way to subscribe every valueUpdate in a single subscribe(saving LOC) or anything like that rather than subscribing four value updates separately if I have to do same thing with each of them. Thanks in advance. :)
You can create only one event handler and "share" it to all observables
var ViewModel = function () {
var self = this;
self.onValueChanged = function (newValue) {
// your task
alert('some work done!');
};
self.val1 = ko.observable();
self.val1.subscribe(self.onValueChanged);
self.val2 = ko.observable();
self.val2.subscribe(self.onValueChanged);
self.sel1 = ko.observable();
self.sel1.subscribe(self.onValueChanged);
self.sel2 = ko.observable();
self.sel2.subscribe(self.onValueChanged);
};
See fiddle
#Accssharma :
The first time a computed is evaluated, the ko engine detects dependencies between observables and computeds. So when you write this :
ko.computed(function(){ val1(); val2(); sel1(); sel2(); doSameWork(); });
Ko registers val1, val2 sel1 and sel2 as a dependency of the computed.
This means if val1 or val2.. changed the computed may change too.
So when an observable (eg val1) is changed the computed needs to be evaluated.
That's why the doSameWork function is called.
I hope it helps.
Related
I have a sortable accordion loaded with a foreach-template loop over a ko.observableArray() named "Tasks".
In the accordion I render the TaskId, the TaskName, and a task Description - all ko.observable().
TaskName and Description is rendered in input/textarea elements.
Whenever TaskName or Description is changed, an item is de-selected, or another item is clicked on, I want to call a function saveEdit(item) to send the updated TaskName and Description to the database via an ajax request.
I need to match the TaskId with the Tasks-array to fetch the actual key/value-pair to send to the saveEdit().
This is the HTML:
<div id="accordion" data-bind="jqAccordion:{},template: {name: 'task-template',foreach: Tasks,afteradd: function(elem){$(elem).trigger('valueChanged');}}"></div>
<script type="text/html" id="task-template">
<div data-bind="attr: {'id': 'Task' + TaskId}" class="group">
<h3><b><span data-bind="text: TaskId"></span>: <input name="TaskName" data-bind="value: TaskName /></b></h3>
<p>
<label for="Description" >Description:</label><textarea name="Description" data-bind="value: Description"></textarea>
</p>
</div>
</script>
This is the binding:
ko.bindingHandlers.jqAccordion = {
init: function(element, valueAccessor) {
var options = valueAccessor();
$(element).accordion(options);
$(element).bind("valueChanged",function(){
ko.bindingHandlers.jqAccordion.update(element,valueAccessor);
});
},
update: function(element,valueAccessor) {
var options = valueAccessor();
$(element).accordion('destroy').accordion(
{
// options put here....
header: "> div > h3"
, collapsible: true
, active: false
, heightStyle: "content"
})
.sortable({
axis: "y",
handle: "h3",
stop: function (event, ui) {
var items = [];
ui.item.siblings().andSelf().each(function () {
//compare data('index') and the real index
if ($(this).data('index') != $(this).index()) {
items.push(this.id);
}
});
// IE doesn't register the blur when sorting
// so trigger focusout handlers to remove .ui-state-focus
ui.item.children("h3").triggerHandler("focusout");
if (items.length) $("#sekvens3").text(items.join(','));
ui.item.parent().trigger('stop');
}
})
.on('stop', function () {
$(this).siblings().andSelf().each(function (i) {
$(this).data('index', i);
});
})
.trigger('stop');
};
};
My first thought was to place the line
$root.SelectedTask( ui.options.active );
in an .on('click') event function where SelectedTask is a ko.observable defined in my viewModel. However, the .on('click') event seems to be called a lot and it's generating a lot of traffic. Also, I canĀ“t quite figure out where to put the save(item) call that sends the selected "item" from Tasks via an ajax-function to the database.
Any help is highly appreciated. Thanks in advance! :)
Whenever TaskName or Description is changed, an item is de-selected, or another item is clicked on, I want to call a function saveEdit(item) to send the updated TaskName and Description to the database via an ajax request.
This sounds like the core of what you want to do. Let's start out with a Task model
function Task (data) {
var self = this;
data = data || {};
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
self.description = ko.observable(data.description);
}
And then we need our View Model:
function ViewModel () {
var self = this;
self.tasks = ko.observableArray();
self.selectedTask = ko.observable();
self.saveTask = function (task) {
$.ajax({ ... });// ajax call that sends the changed data to the server
};
var taskSubscription = function (newValue) {
self.saveTask(self.selectedTask());
};
var nameSubscription, descriptionSubscription;
self.selectedTask.subscribe(function (newlySelectedTask) {
if (newlySelectedTask instanceof Task) {
nameSubscription =
newlySelectedTask.name.subscribe(taskSubscription);
descriptionSubscription =
newlySelectedTask.description.subscribe(taskSubscription);
self.saveTask(newlySelectedTask);// But why?
}
});
self.selectedTask.subscribe(function (currentlySelectedTask) {
if (currentlySelectedTask instanceof Task) {
nameSubscription.dispose();
descriptionSubscription.dispose();
self.saveTask(currentlySelectedTask);// But why?
}
}, null, 'beforeChange');
}
So what's going on here? Most of this should be pretty self explanatory so I'm just going to focus on the subscriptions. We created a taskSubscription function so we're not constantly having it defined every time the self.selectedTask changes.
We have two subscriber functions. The first fires after the selectedTask's value has changed and the second fires before it changes. In both, we verify that the new value is an instance of a Task object. In the after change subscription, we set up two subscriptions on the name and description properties. Then I capture the return value from the subscription function into two private variables. These are used in the before change function to dispose of those subscriptions so that if those Tasks are ever updated when they're not currently selected, then we don't continue to fire off the saveTask function.
I've also added self.saveTask in each of the subscriptions to the selectedTask observable. I asked why in here because, why save it if we don't know if the value has changed or not? You may be making ajax requests needlessly here.
Also, as demonstrated by this code, you can set up these subscriptions to make ajax requests every time the value changes but that may end up making a LOT of requests. A better option might be to set up functionality in your Task model that can track whether or not it is 'dirty' or not. Meaning one or more of its values have changed that requires updating.
function Task (data) {
var self = this;
// Make a copy of the data object coming in and use this to save previous values
self._data = data = $.extend(true, { id: null, name: null, description: null }, data);
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
self.description = ko.observable(data.description);
for (var prop in data) {
if (ko.isSubscribable(self[prop])) {
self[prop].subscribe(function (oldValue) {
data[prop] = oldValue;
}, null, 'beforeChange');
}
}
}
Task.prototype.isDirty = function () {
var self = this;
for (var prop in self._data) {
if (ko.isSubscribable(self[prop])) {
if (self._data[prop] !== self[prop]())
return true;
}
}
return false;
};
And of course you need a way to save it, or make it not dirty
Task.prototype.save = function () {
var self = this;
for (var prop in self._data) {
if (ko.isSubscribable(self[prop])) {
self._data[prop] = self[prop]();
}
}
};
Using the same concept you can also create Task.prototype.revert that does the opposite of what .save does. With all this in place, you could forego setting up the subscriptions on the individual name and description properties. I wanted to show that option to just demonstrate how one might want to use the .dispose method on a subscription. But now you can just subscribe to the selectedTask observable ('beforeChange') and see if the currently selected task that you're about to swap out isDirty. If it is, call the saveTask function, and when that completes, call the .save function on the Task so that it is no longer dirty.
This is probably the route I would go in implementing something like this. The beauty of it is, I haven't written a single line of code that has anything to do with the manipulating the View. You can set the selectedTask any way you see fit. What I would do is, bind the selectedTask observable to a click binding on the <h3> element inside of the accordion. That way, every time a user clicks on any of the accordions, it will potentially save the previously selected task (if any of the property values had changed).
Hopefully that addresses your scenario here of trying to save a Task when certain events are triggered.
I've set up a jsFiddle to demonstrate my problem.
What I'm doing:
I'm using Knockout with a jQuery Datepicker as shown in this question.
My model contains an observableArray which contains objects with date properties. Knockout renders an <input type="text"> for every object, and binds the value to the date using RP Niemeyer's datepicker binding.
What's going wrong:
If the user has a datepicker open when knockout's model changes (e.g., adding a new item), the datepicker stops working correctly. From what I can tell, the last <input type="text"> created while the datepicker is open becomes the new datepicker target. I need to fix the binding so that this does not happen.
Sample HTML:
<ul data-bind="foreach: dateBoxes">
<li>
<span data-bind="text: index"></span>
<input type="text" data-bind="datepicker: date"/>
</li>
</ul>
Sample Javascript:
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function() {
var observable = valueAccessor();
observable($(element).datepicker("getDate"));
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).datepicker("destroy");
});
},
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
//handle date data coming via json from Microsoft
if (String(value).indexOf('/Date(') == 0) {
value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
}
var current = $(element).datepicker("getDate");
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
var model;
var id = 0;
function DateBox(d) {
var self = this;
self.date = ko.observable(d);
self.index = ko.observable(id++);
}
function Model() {
var self = this;
self.dateBoxes = ko.observableArray([]);
self.changeCount = function() {
if (self.dateBoxes().length < 2) {
self.dateBoxes.push(new DateBox(new Date()));
} else if (self.dateBoxes().length > 1) {
self.dateBoxes.splice(0,1);
}
}
self.tick = function() {
self.changeCount();
setTimeout(function() {
self.tick();
}, 5000);
}
self.tick();
}
model = new Model();
ko.applyBindings(model);
Note: This answer isn't complete. However, as it's too large for a comment and probably helpful (towards a solution) anyhow I've taken the liberty and posted it as an answer. Anyone that can complete this answer is invited to do so through an edit or by spinning off into another better answer.
The thing that seems to be spoiling the party (taken from the documentation, emphasis mine):
This will be called once when the binding is first applied to an element, and again whenever the associated observable changes value.
If I hackisly prevent the update from doing its datepicker calls in the first update the datepicker won't break anymore (other issues do arise though). For the init I've added this line at the end:
element.isFirstRun = true;
Then the update method will do the following just before the datepicker calls:
if (element.isFirstRun) {
$(element).val(value);
element.IsFirstRun = false;
return;
}
See this updated fiddle for the results, which are:
the mentioned scenario now updates the correct textbox (a good thing);
the initial value is now a more verbose DateTime string and stays that way after updates (kinda not nice);
Hopefully this will help towards a more complete solution.
I need to pass data from a click: event into another div. Here is a scenario:
There is a link on one side of the page.
<a data-bind="text: Name, click: $root.editAction"></a>
On the other side of the page, there is a hidden div.
<div data-bind="if: $root.editActionShow">
<input type="text" data-bind="value: Name"/>
</div>
I need to be able to pass $data from the click: event, do that hidden div.
Perhaps I am over-thinking this, but my viewModel has many different Actions buried deep in viewModel.DataGroups.DataGroup.ActionDataGroup and there is only 1 HTML form to edit action information, so I can't figure out how to make the form only show that one particular action I want to edit.
Here is another kicker. I prefer not to add any observables to my viewModel. Reason being is that I have to do .toJS() map it at the end, and then convert JSON into XML, which must validate against a pretty strict schema, so having extra elements is a bad thing. It will not pass validation, unless I manually remove them before conversion. However, I can add this.blah = function() {} objects to my viewModel, because .toJS() strips them during conversion.
UPDATE:
Aaand solution to all this is hands down hilarious
viewModel.editAction = function(data) {
viewModel.editActionFormShow(true);
ko.applyBindings(data, $('#myHiddenDiv')[0]);
};
From what I understand, you want something like a 'click-to-edit' function, which can be solved pretty neatly with just 2 custom bindings!
The great advantage about this approach is you won't polute your viewModel with extra observables.
Bindings:
ko.bindingHandlers.hidden = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.visible.update(element, function() {
return!value; });
}
};
ko.bindingHandlers.clickToEdit = {
init: function(element, valueAccessor,allBindingsAccessor){
var value = valueAccessor(),
input = document.createElement('input'),
link = document.createElement('a');
element.appendChild(input);
element.appendChild(link);
value.isEditing = ko.observable(false);
ko.applyBindingsToNode(link,{
text: value,
hidden: value.isEditing,
click: function(){
value.isEditing(true);
}
});
ko.applyBindingsToNode(input,{
value: value,
visible: value.isEditing,
hasfocus: value.isEditing
});
}
};
ViewModel
var vm = {
name: ko.observable()
}
The HTML
<div data-bind="clickToEdit: name"></div>
Working fiddle: http://jsfiddle.net/8Qamd/
All credit goes to Ryan Niemeyer.
I am working on KnockOut validation and so far so good. I do have a question though. I have some code like the following:
shippingMethodModel.Description.extend({ required: true });
And that shows a validation message below BUT does it set a flag or something which I can read to disable my save button?
I had this same need recently, so I'll try to translate what I did based on the line of code you provided above...
Try adding a ko.computed observable similar to the following:
shippingMethodModel.formIsNotValid = ko.computed(function () {
// original line
// var errors = ko.utils.unwrapObservable(ko.validation.group(self));
// ** oops, not "self" in this case
// UPDATED line
var errors = ko.utils.unwrapObservable(ko.validation.group(shippingMethodModel));
return (errors.length > 0);
});
UPDATE
I made a correction in the code above after noticing my error.
For those declaring such a model/class as a function all at once, this code may look similar to the following:
var ShippingMethodModel = function () {
var self = this;
self.shippingMethodId = ko.observable().extend({ required: true });
self.description = ko.observable().extend({ required: true });
self.formIsNotValid = ko.computed(function () {
var errors = ko.utils.unwrapObservable(ko.validation.group(self));
return (errors.length > 0);
});
};
/UPDATE
UPDATE2
Based on input from #ericb in the comments below, I made a change to the way I'm implementing my own solution, which I'll demonstrate by adapting the example code in my update above:
var ShippingMethodModel = function () {
var self = this;
self.shippingMethodId = ko.observable().extend({ required: true });
self.description = ko.observable().extend({ required: true });
self.formIsNotValid = ko.observable(false);
self.validateObservableFormField = function (nameOfObservableToValidate,
data, event) {
for (var prop in data) {
if (prop === nameOfObservableToValidate) {
var theObservable = data[prop];
theObservable.valueHasMutated();
ko.validation.validateObservable(theObservable);
if (theObservable.error) {
self.formIsNotValid(true);
}
else {
if (self.formIsNotValid()) {
var errors =
ko.utils.unwrapObservable(ko.validation.group(self));
self.formIsNotValid(errors.length > 0);
}
}
return;
}
}
};
};
Notice that I've now defined formIsNotValid as an observable, but I'm using the validateObservableFormField function to help me with pre-submit form validity determination. This change ensures that the ko.validation.group function is called only as needed, and that call should only be needed when the observable being validated is valid, but formIsNotValid is true (to handle the case where that current observable was the one that had set formIsNotValid to true).
Here's an example of how I'm doing this:
<input data-bind="value: description,
event: { blur: function(data, event) {
validateObservableFormField('facilityName',
data,
event)
}
}" />
goofy formatting to eliminate horizontal scroll
NOTE: I was already using this technique, but I've adapted it to improve the performance of checking whether or not the form is valid. #Californicated, I realized after my last comment that calling this function from the blur event of validated form fields is why I was seeing my save/submit button toggle between enabled and disabled states.
Thanks again to #ericb for the performance tip.
Further tips, from anyone, are always welcome!
/UPDATE2
Once you've got that in place, disabling the button is a matter of binding to that formIsNotValid computed observable in whatever way makes sense for how you intend to disable the button, e.g. css: { 'ui-state-disabled': formIsNotValid } and/or disable: formIsNotValid and/or some other method(s).
Hope this helps, and let me know if you run into trouble.
I would setup the following:
saveEnabled = ko.computed(function(){
// possible other logic
return shippingMethodModel.Description.isValid();
});
and then in your HTML:
<button data-bind="enable: saveEnabled"> Save </button>
Or, if you have multiple properties on your model, you could do something like:
ko.validation.group(shippingMethodModel);
and then in your HTML:
<button data-bind="enable: isValid"> Save </button>
the group function adds an isValid property to whatever it groups.
I started reimplementing some js code with knockout.js.
I have a singleton with some functions in it:
Dps = {
someFunction: function() {
this.anotherFunction();
},
anotherFunction: function() {
console.log('tehee');
}
}
Now there are also some bindings which calls functions of this singleton:
<input type="text" data-bind="event: { change: Dps.someFunction }" />
The annoying thing is, that the context in the called function is the event, so I can't call this.anotherFunction()
Is there a nice way to get rid of this?
PS: I'm aware that I could do something like Dps.someFunction() instead, but this is not nice in my opinion.
data-bind="event: { change: Dps.someFunction.bind(Dps) }"
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
Your functions behaves as "static"
So either you have to do Dps.anotherFunction but you don't want that, but I don't see why tbh.
You can also call ko.applyBindings(Dps) and then your code would work fine. However I guess that's not what you're looking for either. Probably you have another viewmodel all together, no?
Another solution is to make Dps into a function which you instantiate
On jsfiddle: http://jsfiddle.net/PrbqZ/
<input type="text" data-bind="event: { change: myDps.someFunction }" />
var Dps = function() {
var self = this;
this.someFunction = function() {
self.anotherFunction();
};
this.anotherFunction = function() {
console.log('tehee');
};
}
var myDps = new Dps();
//normally use dom ready, just simulating here
setTimeout(function(){
ko.applyBindings();
}, 500)