Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  168] [ 4]  / answers: 1 / hits: 34366  / 12 Years ago, fri, may 18, 2012, 12:00:00

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?


More From » knockout.js

 Answers
114

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
}

[#85498] Thursday, May 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
;