Is there a way to set the page title by data-binding using Knockout.js?

前端 未结 5 1066
春和景丽
春和景丽 2020-12-11 00:05

I have a viewModel with a Title property. I\'d like to set the page title using that property. Here\'s what I tried already, which didn\'t work:



        
5条回答
  •  暖寄归人
    2020-12-11 00:41

    In my eyes, this situations begs for an observable subscription.

    ...
    {FALL BACK TEXT}
    ...
    

    View Model

    ViewModel = function() {
        var self = this;
        self.PageTitle = ko.observable(null);
        self.PageTitle.subscribe(function(newValue){ document.title = self.PageTitle() });
    
        //change PageTitle to see your handy work in action
        self.PageTitle("Hello World!");
    
    };
    

    EDIT: As an amendment to my previous answer, I'd like to put forth the following. Will my previous suggestion work? Yes, it works very nicely. However, DOM manipulation within the view model itself does not "exactly" follow the MVVM paradigm. The actual "best" approach would be to create a custom binding, which sets the document title on update of a particular observable.

    ...
    {FALLBACK TEXT}
    ...
    

    View Model

    ViewModel = function() {
        var self = this;
        self.PageTitle = ko.observable(null);
    
        self.init = function(){
            self.PageTitle("My page title from an obersvable");
        };
    
        //init the viewmodel
        self.init();
    };
    

    And finally our shiny custom binding to "listen" for changes to the observable (note the use of ONLY the update action)

    ko.bindingHandlers.htmlDocumentTitle = {
        update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
            var fallbackTitle = "My document title";
            var title = ko.unwrap(valueAccessor());
    
            if(!title || title == null && title == "")
                title = fallbackTitle;
    
            document.title = title;
        }
    };
    

    At first glance this solution may appear less scalable, but do keep in mind that we can create "pseudo-inheritance" with Knockout View Models using "call()".

提交回复
热议问题