Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 292
Frank B Avatar asked Dec 26 '22 21:12

Frank B


1 Answers

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.

like image 127
freakish Avatar answered Jan 13 '23 18:01

freakish