简体   繁体   中英

Knockout JS html binding returning weird code instead of html string

function tournamentViewModel(){
    var self= this;
    self.name = ko.observable();
    self.districts = ko.observableArray([new district('Provo',1),new district('Salt Lake City',2),new district('St. George',3)]);
    self.district = ko.observableArray();
    self.regions = ko.observableArray([new region('Utah',1),new region('Idaho',2)]);
    self.region = ko.observableArray();
    self.location = ko.observable();
    self.date = ko.observable();
    self.startTime = ko.observable();
    self.image = ko.observable();
    self.flyer = ko.computed(function(){return '<h1>'+self.name+'</h1>'+self.image},self);
    self.clearImage = function(){
        self.image(''); 
    }
    self.tournamentID = ko.computed(function(){return 't_'+self.district+'_'+self.region+'_'+self.date}, self);
};

The above knockout.js view model seems to be fine except for when I want to bind something to the computed observable flyer . Instead, all I see is the following text:

<h1>function c(){if(0<arguments.length){if(!c.equalityComparer||!c.equalityComparer(d,arguments[0]))c.I(),d=arguments[0],c.H();return this}a.U.La(c);return d}</h1>function c(){if(0<arguments.length){if(!c.equalityComparer||!c.equalityComparer(d,arguments[0]))c.I(),d=arguments[0],c.H();return this}a.U.La(c);return d}

I don't know what's going on here. Below is the binding I'm applying it to. I've tried both html and text bindings.

<span data-bind="text: flyer"></span>

BTW the computed observable tournamentID works great and the syntax seems identical. I think the problem occurs when I use self.name in the computed observable. Any ideas?

Think about it. What do you get? You get the function definition. Because you passed function to your computed . And you need to pass values . You should use:

self.flyer = ko.computed(function(){
    return '<h1>'+self.name()+'</h1>'+self.image();
});

since both name and image are observables (from JavaScript point of view: functions).

I'm not sure why tournamentID is working for you. It shouldn't.

BTW If you are using var self = this; , then you can omit the second argument of computed .

尝试这个

<span data-bind="text: flyer()"></span>

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