Illia Ratkevych
Illia Ratkevych

Reputation: 3711

Apply knockout bindings in specific context

I'm new in Require as well in Knockout. An now I'm trying to integrate my Knockout viewmodel into Reuire.js architecture.

I have 5 js files:

This is how I call require.js from index.html:

<script data-main="/scripts/app" src="/scripts/require.js"></script>

And here is entry point script app.js:

require.config({
    baseUrl: "/scripts",
    paths: {
        "jquery": "jquery-2.0.3",
        "knockout": "knockout-2.2.0",
        "MyViewModel": "./ko-model/MyViewModel"
    }
});

require([
    "jquery",
    "knockout",
    "MyViewModel"
],
    function ($, ko, MyViewModel) {
        // LOGIC:
        $(function () {
            ko.applyBindings(
                new MyViewModel(),
                $("#myId")
            );
        });        
    });

Here is MyViewModel.js module:

define(
    'MyViewModel',
    ["knockout"],
    function (ko) {
        return function MyViewModel() {
            // MyViewModel implementation
            ...
        };
    });

This is works fine for me. But.

As you can see in app.js I have:

function ($, ko, MyViewModel) {
    // LOGIC:
    $(function () {
        ko.applyBindings(
            new MyViewModel(),
            $("#myId")
        );
    });
}

And I don't like this. I would rather prefer don't use jQuery here and specify knockout context somehow like this:

function ($, ko, MyViewModel) {
    // LOGIC:
    ko.applyBindings(
        new MyViewModel(),
        document.getElementById("myId")
    );
}

But in this case knockout bindings just doesn't work. It seems that document.getElementById("myId") doesnt work here. And I don't know why. (My best guess was that document hasn't loaded yet when ko.applyBindings() called).

Therefore I have next question:

How can I escape using jQuery in the LOGIC section, but still specify knockout context?

I would appreciate any suggestions for improving my code.

Upvotes: 0

Views: 102

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40296

Yes, it cannot find the id because most probably the document hasn't finished loading yet. This problem will most probably arise if the <script>s are in the <head>. You require-friendly solution is the domReady plugin. From the docs:

require(["jquery", "knockout", "MyViewModel", "domReady"],
function($, ko, MyViewModel, domReady) {
    domReady(function () {
        // your code here, document is initialized
    });
});

Upvotes: 1

Related Questions