Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unsubscribe the subscribed function in knockout?

I already subscribe the function to listen the property value change using ko.

var self = this; $( document ).ready( function () {  var postbox = new ko.subscribable(); var myViewModel = {     FirstName: ko.observable( "Bert" ),     LastName: ko.observable( "pual" ) }; var sub = null; for ( var i in myViewModel ) {     var model = myViewModel[i];     model.subscribe( self.notifyChange.bind( model, i ) );  }  $( '#unsubscribeButton' ).click( function () {     // here i want to unsubscribe. } );  ko.applyBindings( myViewModel );   });  notifyChange = function ( PropName, newValue ) { var self= this; );     } 

here i want to unsubscribe the notifyChange from myViewModel's property one by one, how to do this?

like image 225
BalaKrishnan웃 Avatar asked May 18 '12 12:05

BalaKrishnan웃


People also ask

What is applyBindings in knockout?

applyBindings do, The first parameter says what view model object you want to use with the declarative bindings it activates. Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.

What does Ko observable do?

Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.


1 Answers

Store results of call to subscriptions in a variable (or, in your case, in an array).

When you want to unsubscribe, simply call dispose on each subscription.

Fully described here - http://knockoutjs.com/documentation/observables.html

Your code will look like this:

//store subscriptions in array var subscriptions = [];  for ( var i in myViewModel ) {     var model = myViewModel[i];     subscriptions.push(model.subscribe( self.notifyChange.bind( model, i ) )); }   //unsubscribe for(var i in subscriptions) {     subscriptions[i].dispose(); //no longer want notifications } 
like image 180
Artem Avatar answered Sep 24 '22 02:09

Artem