i have a view model with an observable array. Its populated with some json:
this.socialTiles = ko.observableArray([]);
ko.computed(function () {
jQuery.getJSON( this.apiURL+"&callback=?", function (data) {
var theData = data.entries;
tilesModel.socialTiles(theData);
console.dir(theData);
});
}, tilesModel);
for each item in the model, i build an li using template:
<ul id="tiles-ul" data-bind="template: {name:'twitter_template', foreach:socialTiles}">
<script type="text/html" id="twitter_template">
<li class="social-tile box-shadow">
<div class="header">
<div class="header-img">
<img data-bind="attr: { src: actor.avatar}">
</div>
<div class="name_and_time">
<span class="full-name" data-bind="text: actor.title"></span>
<span class="twitter-name" data-bind="text: actor.id"></span>
<span class="how-long-ago" > 5 minutes ago </span>
</div>
</div>
<div class="message-content" data-bind="html: object.content">
</div>
<div class="footer">
<div class="social-icon-twitter">
</div>
</div>
<span data-bind="text: $index"></span>
</li>
</script>
id like to data-bind the text of an element to be a result of a function, with the current data from the model used as an argument . example:
actor.id is a string containing a twitter url of a user (like "http://twitter.com/iamdiddy")
i'd like to pass that string to a function and return a "#iamdiddy" representation.
<span class="twitter-name" data-bind="text: getTwitterTag(actor.id)"></span>
in the view model
function getTwitterTag("twURL"){
return ... whatever;
}
how can I do this (call a function with argument, not extract the #... )? Does knockout support this functionality?
Bind properties in a component's template to properties in the component's JavaScript class. In the template, surround the property with curly braces, { property } . To compute a value for the property, use a JavaScript getter in the JavaScript class, get property (){} .
A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
Try changing
<span class="twitter-name" data-bind="text: getTwitterTag(actor.id)"></span>
to
<span class="twitter-name" data-bind="text: $root.getTwitterTag($data)"></span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With