سؤال

I am trying to create a web page with form that once user change any field, the validation and update commit immediately rather than letting user to click on submit button. I am using Knockout.js and mapping plugin. I know I can achieve this by creating a computed field for each original fields, but this kind of work is tedius and dumb, is there good practice to create a general listener to listen on any changes in any fields and update backend respectively?

هل كانت مفيدة؟

المحلول

In order to subscribe to any change you could use ko.toJS() method. Actually it allows to walk through object graph and unwrap observables. As your probably know when you use ko.computed it subscribes to all reads of observables fields and re-evaluate on every change. So if you use code like this:

ko.computed(function() {
   ko.toJS(viewModel);
   // update data on server
});

Also you should pay attention that this piece of code will update data on server right after initialization. It could be easily avoided. Please checkout this example: http://jsfiddle.net/UAxXa/embedded/result/

Also I think you might want to send only changed data to server. You could incorporate ko.editbales plugin ( https://github.com/romanych/ko.editables ) and some KO under-hood knowledge. Please checkout this sample: http://jsfiddle.net/romanych/RKn5k/

I hope it could help you.

نصائح أخرى

You've got several options but if you want a single listener, one good way is to use the same code I used to create a change tracker. It simply listens for the observable changes. Its about 19 lines of code. You can grab this and instead of using it for change tracking, just wire in a method that saves the changes when they occur.

To Setup change tracking, add this tracker property to your view model:

viewModel.tracker = new ChangeTracker(viewModel); 

Hook these into your view to determine when changes occur:

viewModel.tracker().somethingHasChanged(); 

Hook this into your view model when you want to reset state in functions (ex: load, save):

viewModel.tracker().markCurrentStateAsClean; 

Optionally, you can pass your own hashFunction for state tracking, too.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top