Search code examples
javascriptknockout.jsattr

call model function from attr in knockout js to get dynamic attributes


I am not so fluent in knockout js, so this could be a silly one.

my model looks like this:

  var myViewModel = {
    personName: 'Bob',
    attributesAttached: 'title:SampleTitle',
    getTitle : function(){
    return "SampleTitle";
    },
    getAttributeKeyValuePair : function(){
       return "title : SampleTitle";
    },
     getAttributeKeyValuePairCollection : function(){
       return "title : SampleTitle , href : test.html";
    }

    };

ko.applyBindings(myViewModel);

My Working html looks like this :

The name is
<span data-bind="text: personName,attr: { title :  getTitle() }"></span>

I want to achieve this :

not working

The name is
<span data-bind="text: personName,attr: { getAttributeKeyValuePair() }"></span>

Because later on some property or method would give me a collection of attribute key value pairs

not working

The name is
<span data-bind="text: personName,attr: { getAttributeKeyValuePairCollection() }"></span>

How can i make that work so that i can have my attribute names and their respective values generated dynamically(as and when my JSON is fully processed)


Solution

  • The attr binding-handler is expecting an object, where each property-name is correspondent to the attribute name, and the property-value to the attribute value.

    So your getAttributeKeyValuePairCollection() method simply needs to return object:

    getAttributeKeyValuePairCollection: function() {
       return {
              href: 'test.html',
              title: 'SimpleTitle'
              };
    }
    

    And in your data-bind:

    <span data-bind="text: personName, attr: getAttributeKeyValuePairCollection()"></span>
    

    See Documentation