Is it safe to call ko.applyBindings without any pa

2019-08-08 15:59发布

问题:

This is the only official doc I could find on ko.applyBindings():

http://knockoutjs.com/documentation/observables.html

It's not a real formal written document that says exactly what is optional/etc. In testing it appears that calling ko.applyBindings() allows for bindings on a global scope, and it appears to work fine. Has anyone that studied the source code (or know more about KO than I do), know if this is safe or not? Any performance issues?

This is the start of my "app" object for an SPA I'm working on:

var app = {

self: this,
datacontext: new DataContext(),
dataservice: new DataService(),
viewModels: {
    main: new MainViewModel(),
    folderDetails: new FolderDetailsViewModel()
},

init: function() {

    ko.applyBindings();

    Sammy(function() {

        this.get('#:folder', function() {
            self.doFolderRoute(this.params.folder);
        });

        // Override this function so that Sammy doesn't mess with forms
        this._checkFormSubmission = function(form) {
            return (false);
        };

    }).run();

},

doFolderRoute: function(id) {
    console.log("doFolderRoute: " + id);
}
}

I could do ko.applyBindings(self.viewModels), to restrict data-bind to the models... but I kind of like the freedom of being able to bind to anything and don't mind (even like) typing out app.viewModels.main in my code, vs just "main".

回答1:

By using ko.applyBindings(), Knockout won't know about your view model. $root won't be set and neither will $data at the root level. Obviously, you can simply not reference those variables. Also the event bindings pass $data to the event handler function, which in this case will be undefined.



回答2:

Just FYI - This is my updated app (still work in progress obviously):

I figured out self: this I had in the original code was pointing to window, so obviously that was a bad idea and one reason I was getting weird results when I tried ko.applyBindings(self.viewModels).

var app = {

datacontext: new DataContext(),
dataservice: new DataService(),
viewModels: {
    main: new MainViewModel(),
    folderDetails: new FolderDetailsViewModel()
},

init: function() {

    ko.applyBindings(app.viewModels);

    Sammy(function() {

        this.get('#:folder', function() {
            self.doFolderRoute(this.params.folder);
        });

        // Override this function so that Sammy doesn't mess with forms
        this._checkFormSubmission = function(form) {
            return (false);
        };

    }).run();

    widgetLib.init();

},

doFolderRoute: function(id) {
    console.log("doFolderRoute: " + id);
}
}


标签: knockout.js