简体   繁体   中英

How do I include knockout viewmodel defined in separate javascript file in my view?

I am new to using knockout and I have created a view model that was originally in my view which worked and updated the text as I entered into the textbox but after I moved the knockout viewmodel from my view into a separate javasctipt file and included it in the view referencing it in the script tags the knockout bindings are not applied. What else do I need to do? How do I get this to work? I don't want to have script tags in every view referencing knockout and having the view models defined in the view, I want the view models in separate files.

Here is my view model which worked when I include it within script tags in my view. I have moved it to a separate file called UserDashboardViewModel.js and including it in my view but it does not work when in a separate file, only when included in the view:

var viewModel = {
    monkey: ko.observable(),
    array: ko.observableArray(),
    AddAnimal: function () 
    {
        this.array.push(this.monkey());
    }
};

ko.applyBindings(viewModel);

And in my view:

<script type='text/javascript' src='~/Scripts/knockout-3.4.0.js'></script>
    <script type='text/javascript' src='~/Scripts/UserDashboardViewModel.js></script>

<h1 data-bind="text: monkey">text</h1>
... other knockout data-bindings that do not work

If your script tags are in the head of your HTML page then you need to make sure you call ko.applyBindings() when the DOM is loaded.

// with jQuery 
$(document).ready(function(){ko.applyBindings(viewModel); });

// shorter jQuery version 
$(function(){ ko.applyBindings(viewModel); });

// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){ 
    ko.applyBindings(viewModel);
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM