knockoutjs subscribe method is invoked 2 times

In knockoutjs subscribe method, I also set the value of property inside subscribe method, that why the method is invoked 2 times, first one when the value is change in UI and second time when value is changed inside subscribe method.

Anyone know how to avoid this case.

This is my sample code:

var ViewModel = function(first) {
    var self = this;
    self.firstName = ko.observable(first);
    self.firstName.subscribe(function(newValue) {
        alert(newValue);
        self.firstName(newValue.toUpperCase());       
    });

};

Also put to jsfiddle http://jsfiddle.net/ndkhoiits/4ABuq/

Answers


In your case, you would probably need a computed observable with a getter and setter

var ViewModel = function(first) {
    var self = this;
    self.firstName = ko.observable(first);
    self.firstNameForView = ko.computed({        
        read: function () {            
            return self.firstName();
        },        
        write: function (value) {            
            self.firstName(value.toUpperCase());
        },        
        owner: this    
    });
};

Now use the firstNameForView in your data binding.


Need Your Help

What's the equivalent of rustc_serialize::Json in serde?

json rust

Since the serde library is going to become a replacement of rustc_serialize, I'm trying to refactor my library to work with it. I can't figure out what the corresponding type of rustc_serialize::Js...

does a sequel models generator exists?

ruby orm sequel ramaze

I'm looking for a ruby class that could generate the sequel model file for Ramaze after reading the definition of the table in a mySQL database.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.