Is it safe to call ko.applyBindings without any parameters?

风格不统一 提交于 2019-12-24 16:03:08

问题


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);
}
}


来源:https://stackoverflow.com/questions/14903650/is-it-safe-to-call-ko-applybindings-without-any-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!