I am new to Knockoutjs and JavaScript, and need some advice.
In my HTML (View) page, I am trying to show a text property from my Javascript object (Model), which looks something like:
var object = function() {
this.text = "blah blah blah";
}
In my Object's ViewModel, I have this:
var objectViewModel= function (object) {
var content = ko.observable(object); // or is it object.text() ?
self.section = function() {
return content.text; //or is it content ?
}
}
And in my view, I have this:
<span data-bind="text:section"></span>
My main question is how do I make the HTML show a model's property (the text) via viewmodel? I commented in my other questions, and would like some help.
Thanks in advance!
So I'd recommend this post as a good read.
To answer both of the additional commented questions: It all depends on what you passed as the parameter . That important bit of information would be provided when you instantiate your viewmodel, which you left out.
As specified, you'll need to ko.applyBindings(new objectViewModel(new object()))
. Secondly, you have self
, where did it come from? Make it this
or declare var self = this;
or provide the rest of the code from which that variable is coming from.
Next, from within the section
function you need to "read" your content observable:
return content().text
Finally, in your view you need to execute section
:
<span data-bind="text:section()"></span>
As an additional consideration, you could make section
a computed observable with a dependency on content
.
this.section = ko.computed(function() {
return content().text;
})
which removes the need to execute in the view. Check out this fiddle with two different scenarios depicted.
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.