Skip to content Skip to sidebar Skip to footer

Data-bind "attr" Doesn't Work (?)

The Goal Read the data-product-id from DOM added by KnockoutJS. The problem I have the following markup:
  • Solution 1:

    looks like you have a timing problem there.

    Please note, that knockoutjs first goes through your js models and then filles the view with content. So if you are testing or in your case iteration over some DOM structure, you run straight into a timing error.

    Try to rethink what you are doing there. As knockoutjs is providing the html with data, you already have all data in your js code. To me this looks like a work-a-round.

    eg: Your template:

    <!-- ko foreach: Summary.products --><lidata-bind="attr: { 'data-product-id': id }"></li><!-- /ko -->

    in knockoutjs you already have a list of products and the particular product-id. So all you need to do is to check the length of your list? Or do I miss something there?

    If I get it wrong, and you just want to trigger another javascript which is doing something when your list is rendered, try to trigger some event when knockoutjs has filled your page with content. Or trigger your javascript after the dom is ready.

    Solution 2:

    I'm guessing you're doing the $.each before your DOM is ready (before Knockout has made its modifications).

    Take the each out of your ViewModel and put it in this code-block:

    $(function() {
        $(element).each(function () {
            var $productId = $(this).closest("li").data("product-id"),
            $match = $(".summary")
                     .find("li[data-product-id=" + $productId + "]").length > 0;
            console.log($match);
        });
    });
    

    Solution 3:

    Accordling to this fiddle, it should work.

    Are sure you execute the $(element).each after applied bindings ?

    JS :

    var vm = { id:'myID-product'};    
    ko.applyBindings(vm);    
    var element = $("#myID").data("product-id");             
    console.log(element);
    

    View :

    <li data-bind="attr: { 'data-product-id': id }"id="myID">
    

    So, I think you should :

    • Create the VM instance
    • Apply binding
    • Call an init function in which you call the $(element).each
  • Post a Comment for "Data-bind "attr" Doesn't Work (?)"