0

In my _layout.cshtml I have a partial view that includes js trough requirejs.

<script data-main="/Scripts/Search" src="/Scripts/require.js"></script>

In this js file I use the following to populate a knockout vm.

    $.getJSON("/Search/Index", function (data) {
        self.availableCities(data.AvailableCities);
    });

This works well on all pages except when my main view also has an ajax request.

    <script data-main="/Scripts/Index" src="/Scripts/require.js"></script>


    $.getJSON("/Property/All", function (data) {
        self.properties(data);
    });

Here is my require config, it is the same for the partial and the main view.

require.config({
    baseUrl: "/Scripts",
    paths: {
        "text": "text",
        "knockout": "knockout-3.3.0",
        "jquery": "jquery-2.1.3.min"
    },
    shim: {
        "jquery": { exports: "$" }
    }
});

When the main page has an ajax request only this request is fired, I am not sure how to fix this. It looks like a configuration issue, tested it in both Firefox an Chrome so it does not appear to be browser specific.

Arnold Wiersma
  • 165
  • 1
  • 4
  • 17

1 Answers1

0

It turns out having multiple <script data-main="/Scripts/Search" src="/Scripts/require.js"></script> tags in one page isn't such a bright idea.

I figured it out after some more research, this question has a good solution if you run into a similar problem.

Basically you need one 'main.js' file and add the other page components via the require logic.


Edit:

Doing this may result in the following knockout error:

Error: You cannot apply bindings multiple times to the same element.

To fix this I have used the following binding handler:

ko.bindingHandlers.stopBinding = {
    init: function () {
        return { controlsDescendantBindings: true };
    }
};

To enable this binding handler on containerless elements use the following:

ko.virtualElements.allowedBindings.stopBinding = true;

Apply the following binding around the partial view. To prevent the main-page from binding to the elements in the partial.

<!-- ko stopBinding: true-->
<!-- /ko -->

Finally use ko.applyBinings on the partialview like this:

ko.applyBindings(new partialViewModel(), document.getElementById("your-partial"));
Community
  • 1
  • 1
Arnold Wiersma
  • 165
  • 1
  • 4
  • 17