SteveSanderson / knockout-es5

Knockout.js meets ECMAScript 5 properties
157 stars 39 forks source link

Question: Custom Bindings and Subscribe? #11

Closed brigand closed 9 years ago

brigand commented 10 years ago

Hey @SteveSanderson,

I'm writing a library of custom bindings. Is there any way to subscribe in the init function when I'm just getting the observable passed?

My current binding:

    init: function(element, valueAccessor){
        var $el = $(element);

        // Toggle the observable on click
        $(element).click(function(){
            var observable = valueAccessor();

            // Update the observable (true or false)
            // this also effects the class change
            observable(!ko.unwrap(observable));
        });

        var updateClass = function(){
            // if we set it to true, add the "active" class
            if (!!ko.unwrap(valueAccessor())) {
                $el.addClass('active');
            }

            // otherwise, remove it
            else {
                $el.removeClass('active');
            }
        };

       /** throwing an error because I'm calling subscribe on a boolean **/
        valueAccessor().subscribe(updateClass);

        // invoke immediately to get the initial class correct
        updateClass();
    }

Also, how can I set the observable?

brigand commented 10 years ago

Do I need to only accept tracked objects? I can do that if it's the only way (for writing, specifically).

Side question: do I need to declare my binding is two-way, like the ones in the docs? What does that do?