Ravi
Ravi

Reputation: 3210

Is there a way to achieve multiple data binding for a single element in KnockoutJS?

I am a pretty new to the wonderful MVC framework KnockoutJS. Is it possible to data bind multiple attributes together?

I want to data-bind CSS and style together for a particular element. For example,

I want to data-bind style and CSS together for an element, say h2 based on some conditions.

Upvotes: 5

Views: 8653

Answers (1)

photo_tom
photo_tom

Reputation: 7342

Yes, you can data bind multiple attributes. You need to separate each attribute with a comma.

For styling, it sort of depends on what you really want to do. As a start, check the knockout documentation -

  • CSS Binding
  • Style Binding
  • For really customizable style, take a look at Ryan Niemeyer's fiddle at Dynamic Styling,

        var viewModel = {
            size: ko.observable(2)
        };
    
        viewModel.style = ko.dependentObservable(function() {
            return "h2 { font-size: " + this.size() + "em }";
        }, viewModel);
    
        ko.applyBindings(viewModel);
    

Upvotes: 12

Related Questions